Source file src/crypto/fips140/testdata/enforcement_test.go

     1  // Copyright 2025 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package fips140_test
     6  
     7  import (
     8  	"crypto/des"
     9  	"crypto/fips140"
    10  	"testing"
    11  )
    12  
    13  func expectAllowed(t *testing.T, why string, expected bool) {
    14  	t.Helper()
    15  	result := isAllowed()
    16  	if result != expected {
    17  		t.Fatalf("%v: expected: %v, got: %v", why, expected, result)
    18  	}
    19  }
    20  
    21  func isAllowed() bool {
    22  	_, err := des.NewCipher(make([]byte, 8))
    23  	return err == nil
    24  }
    25  
    26  func TestDisabled(t *testing.T) {
    27  	expectAllowed(t, "before enforcement disabled", false)
    28  	fips140.WithoutEnforcement(func() {
    29  		expectAllowed(t, "inside WithoutEnforcement", true)
    30  	})
    31  	// make sure that bypass doesn't live on after returning
    32  	expectAllowed(t, "after WithoutEnforcement", false)
    33  }
    34  
    35  func TestNested(t *testing.T) {
    36  	expectAllowed(t, "before enforcement bypass", false)
    37  	fips140.WithoutEnforcement(func() {
    38  		fips140.WithoutEnforcement(func() {
    39  			expectAllowed(t, "inside nested WithoutEnforcement", true)
    40  		})
    41  		expectAllowed(t, "inside nested WithoutEnforcement", true)
    42  	})
    43  	expectAllowed(t, "after enforcement bypass", false)
    44  }
    45  
    46  func TestGoroutineInherit(t *testing.T) {
    47  	ch := make(chan bool, 2)
    48  	expectAllowed(t, "before enforcement bypass", false)
    49  	fips140.WithoutEnforcement(func() {
    50  		go func() {
    51  			ch <- isAllowed()
    52  		}()
    53  	})
    54  	allowed := <-ch
    55  	if !allowed {
    56  		t.Fatal("goroutine didn't inherit enforcement bypass")
    57  	}
    58  	go func() {
    59  		ch <- isAllowed()
    60  	}()
    61  	allowed = <-ch
    62  	if allowed {
    63  		t.Fatal("goroutine inherited bypass after WithoutEnforcement return")
    64  	}
    65  }
    66  

View as plain text