Source file src/crypto/fips140/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  	"crypto/internal/cryptotest"
    11  	"testing"
    12  )
    13  
    14  func expectAllowed(t *testing.T, why string, expected bool) {
    15  	t.Helper()
    16  	result := isAllowed()
    17  	if result != expected {
    18  		t.Fatalf("%v: expected: %v, got: %v", why, expected, result)
    19  	}
    20  }
    21  
    22  func isAllowed() bool {
    23  	_, err := des.NewCipher(make([]byte, 8))
    24  	return err == nil
    25  }
    26  
    27  func TestWithoutEnforcement(t *testing.T) {
    28  	if !fips140.Enforced() {
    29  		cryptotest.RerunWithFIPS140Enforced(t)
    30  		return
    31  	}
    32  
    33  	t.Run("Disabled", func(t *testing.T) {
    34  		expectAllowed(t, "before enforcement disabled", false)
    35  		fips140.WithoutEnforcement(func() {
    36  			expectAllowed(t, "inside WithoutEnforcement", true)
    37  		})
    38  		// make sure that bypass doesn't live on after returning
    39  		expectAllowed(t, "after WithoutEnforcement", false)
    40  	})
    41  
    42  	t.Run("Nested", func(t *testing.T) {
    43  		expectAllowed(t, "before enforcement bypass", false)
    44  		fips140.WithoutEnforcement(func() {
    45  			fips140.WithoutEnforcement(func() {
    46  				expectAllowed(t, "inside nested WithoutEnforcement", true)
    47  			})
    48  			expectAllowed(t, "inside nested WithoutEnforcement", true)
    49  		})
    50  		expectAllowed(t, "after enforcement bypass", false)
    51  	})
    52  
    53  	t.Run("GoroutineInherit", func(t *testing.T) {
    54  		ch := make(chan bool, 2)
    55  		expectAllowed(t, "before enforcement bypass", false)
    56  		fips140.WithoutEnforcement(func() {
    57  			go func() {
    58  				ch <- isAllowed()
    59  			}()
    60  		})
    61  		allowed := <-ch
    62  		if !allowed {
    63  			t.Fatal("goroutine didn't inherit enforcement bypass")
    64  		}
    65  		go func() {
    66  			ch <- isAllowed()
    67  		}()
    68  		allowed = <-ch
    69  		if allowed {
    70  			t.Fatal("goroutine inherited bypass after WithoutEnforcement return")
    71  		}
    72  	})
    73  }
    74  

View as plain text