Skip to content

Commit f52f463

Browse files
committed
feat(node): gate certificate signing on the first clock sync
Signed-off-by: Bugs5382 <12115015+Bugs5382@users.noreply.github.com>
1 parent 675172f commit f52f463

4 files changed

Lines changed: 206 additions & 0 deletions

File tree

‎internal/node/node_test.go‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -494,3 +494,32 @@ func TestConfigStoreCurrentWithNoConfigIsErrNoConfig(t *testing.T) {
494494
t.Fatalf("Current with no persisted config = %v, want ErrNoConfig", err)
495495
}
496496
}
497+
498+
// The time-sync state is read per GetStatus, so the first good sync after boot
499+
// shows up without a reboot. Unwired, the field stays unset.
500+
func TestStatusProviderReportsTimeSync(t *testing.T) {
501+
s, ctx := newTestStore(t)
502+
ts := &cryptosv1.TimeSyncStatus{State: cryptosv1.TimeSyncState_TIME_SYNC_STATE_PENDING}
503+
sp, err := NewStatusProvider(StatusConfig{
504+
Store: s,
505+
Role: cryptosv1.NodeRole_NODE_ROLE_ISSUING,
506+
TimeSync: func() *cryptosv1.TimeSyncStatus { return ts },
507+
})
508+
if err != nil {
509+
t.Fatalf("NewStatusProvider: %v", err)
510+
}
511+
if st, _ := sp.Status(ctx); st.GetTimeSync() != ts {
512+
t.Fatalf("time_sync = %v, want %v", st.GetTimeSync(), ts)
513+
}
514+
ts = &cryptosv1.TimeSyncStatus{State: cryptosv1.TimeSyncState_TIME_SYNC_STATE_SYNCED}
515+
if st, _ := sp.Status(ctx); st.GetTimeSync().GetState() != cryptosv1.TimeSyncState_TIME_SYNC_STATE_SYNCED {
516+
t.Fatalf("a later sync was not reflected: %v", st.GetTimeSync())
517+
}
518+
bare, err := NewStatusProvider(StatusConfig{Store: s, Role: cryptosv1.NodeRole_NODE_ROLE_ROOT})
519+
if err != nil {
520+
t.Fatal(err)
521+
}
522+
if st, _ := bare.Status(ctx); st.GetTimeSync() != nil {
523+
t.Fatalf("unwired time sync must leave the field unset: %v", st.GetTimeSync())
524+
}
525+
}

‎internal/node/providers.go‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ type StatusConfig struct {
6767
// Resolver reports the DNS resolver written at boot; nil leaves
6868
// NodeStatus.resolver unset.
6969
Resolver func() *cryptosv1.ResolverStatus
70+
// TimeSync reports the SNTP clock synchronisation state; nil leaves
71+
// NodeStatus.time_sync unset.
72+
TimeSync func() *cryptosv1.TimeSyncStatus
7073
}
7174

7275
// StatusProvider adapts a Store + live health probes to grpc.StatusProvider.
@@ -109,6 +112,10 @@ func (p *StatusProvider) Status(ctx context.Context) (*cryptosv1.NodeStatus, err
109112
if p.cfg.Resolver != nil {
110113
resolver = p.cfg.Resolver()
111114
}
115+
var timeSync *cryptosv1.TimeSyncStatus
116+
if p.cfg.TimeSync != nil {
117+
timeSync = p.cfg.TimeSync()
118+
}
112119
return &cryptosv1.NodeStatus{
113120
Role: p.cfg.Role,
114121
IdentityState: phase.IdentityState(),
@@ -122,6 +129,7 @@ func (p *StatusProvider) Status(ctx context.Context) (*cryptosv1.NodeStatus, err
122129
FleetManager: cryptosv1.FleetManagerState_FLEET_MANAGER_STATE_NOT_ENROLLED,
123130
RevocationPreflight: preflight,
124131
Resolver: resolver,
132+
TimeSync: timeSync,
125133
}, nil
126134
}
127135

‎internal/node/signer.go‎

Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@ import (
2626
"encoding/asn1"
2727
"encoding/pem"
2828
"errors"
29+
"log"
2930
"net"
3031
"net/url"
3132
"slices"
@@ -78,6 +79,15 @@ type CASigner struct {
7879
// certificate is returned: if recording fails, issuance fails and the
7980
// certificate is NOT returned, so every returned certificate is tracked.
8081
recordIssued func(ctx context.Context, der []byte, profileName string) error
82+
83+
// clockSynced reports whether the node's clock gate is open: true with no
84+
// time source, or once a configured source has synced this boot. Nil
85+
// (no time sync wired) never gates, the same as a node with no source.
86+
clockSynced func() bool
87+
88+
// issued is told the notBefore of every certificate returned, so the
89+
// clock floor can be raised past it. Nil is a no-op.
90+
issued func(notBefore time.Time)
8191
}
8292

8393
// NewCASigner constructs a CASigner from a key loader, an issuer-cert getter,
@@ -97,6 +107,44 @@ func (s *CASigner) WithPreflight(ok func(ctx context.Context) bool) *CASigner {
97107
return s
98108
}
99109

110+
// WithClockGate wires the clock gate and returns the same CASigner for
111+
// chaining. While synced reports false, every signing path refuses with
112+
// FailedPrecondition before the CA key is loaded, unless the live config sets
113+
// pki.allow_unsynced_clock. The dates a CA stamps are only as good as its
114+
// clock, and a node whose time source has never answered may be far off.
115+
func (s *CASigner) WithClockGate(synced func() bool) *CASigner {
116+
s.clockSynced = synced
117+
return s
118+
}
119+
120+
// WithIssuedHook wires a callback told the notBefore of every certificate the
121+
// signer returns, and returns the same CASigner for chaining.
122+
func (s *CASigner) WithIssuedHook(fn func(notBefore time.Time)) *CASigner {
123+
s.issued = fn
124+
return s
125+
}
126+
127+
// checkClock applies the clock gate for one signing request.
128+
func (s *CASigner) checkClock(cfg *config.Config, what string) error {
129+
if s.clockSynced == nil || s.clockSynced() {
130+
return nil
131+
}
132+
if cfg.PKI.AllowUnsyncedClock {
133+
log.Printf("node: WARNING: %s signed on an unsynced clock: the time source has not synced this boot and pki.allow_unsynced_clock is set", what)
134+
return nil
135+
}
136+
log.Printf("node: %s refused: the clock has not synced with its configured time source this boot", what)
137+
return status.Error(codes.FailedPrecondition,
138+
"node: the clock has not synced with its configured time source yet; signing is refused (set pki.allow_unsynced_clock to override)")
139+
}
140+
141+
// noteIssued reports a returned certificate's notBefore to the issued hook.
142+
func (s *CASigner) noteIssued(notBefore time.Time) {
143+
if s.issued != nil {
144+
s.issued(notBefore)
145+
}
146+
}
147+
100148
// WithRecorder wires the issued-certificate recorder and returns the same
101149
// CASigner for chaining. When set, IssueLeaf and SignSubordinate record every
102150
// minted certificate before returning it; if recording fails the issuance
@@ -131,6 +179,9 @@ func (s *CASigner) SignSubordinate(ctx context.Context, csrDER []byte, profileNa
131179
if !prof.BasicConstraints.IsCA {
132180
return nil, "", nil, status.Errorf(codes.InvalidArgument, "node: profile %q is not a CA profile", profileName)
133181
}
182+
if err := s.checkClock(cfg, "subordinate CA signing"); err != nil {
183+
return nil, "", nil, err
184+
}
134185

135186
issuerCert, err := s.issuer(ctx)
136187
if err != nil {
@@ -160,6 +211,7 @@ func (s *CASigner) SignSubordinate(ctx context.Context, csrDER []byte, profileNa
160211
if err := s.record(ctx, der, profileName); err != nil {
161212
return nil, "", nil, err
162213
}
214+
s.noteIssued(p.NotBefore)
163215

164216
chainDER = [][]byte{der}
165217
var sb strings.Builder
@@ -322,6 +374,9 @@ func (s *CASigner) issueLeaf(ctx context.Context, csrDER []byte, profileName str
322374
return nil, nil, nil, nil, status.Error(codes.FailedPrecondition,
323375
"node: a ROOT node refuses to issue leaf certificates without the irreversible acknowledgement")
324376
}
377+
if err := s.checkClock(cfg, "leaf issuance"); err != nil {
378+
return nil, nil, nil, nil, err
379+
}
325380

326381
issuerCert, err = s.issuer(ctx)
327382
if err != nil {
@@ -357,6 +412,7 @@ func (s *CASigner) issueLeaf(ctx context.Context, csrDER []byte, profileName str
357412
if err := s.record(ctx, der, profileName); err != nil {
358413
return nil, nil, nil, nil, err
359414
}
415+
s.noteIssued(p.NotBefore)
360416
return der, pemBytes, issuerCert, vcap, nil
361417
}
362418

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
package node
2+
3+
/*
4+
Apache License 2.0
5+
6+
Copyright 2026 Shane
7+
8+
Licensed under the Apache License, Version 2.0 (the "License");
9+
you may not use this file except in compliance with the License.
10+
You may obtain a copy of the License at
11+
12+
http://www.apache.org/licenses/LICENSE-2.0
13+
14+
Unless required by applicable law or agreed to in writing, software
15+
distributed under the License is distributed on an "AS IS" BASIS,
16+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17+
See the License for the specific language governing permissions and
18+
limitations under the License.
19+
*/
20+
21+
import (
22+
"context"
23+
"crypto"
24+
"strings"
25+
"testing"
26+
"time"
27+
28+
"google.golang.org/grpc/codes"
29+
"google.golang.org/grpc/status"
30+
31+
"github.com/CryptOS-PKI/cryptos/internal/config"
32+
)
33+
34+
// A configured time source that has not synced yet closes the gate: every
35+
// signing path refuses with FailedPrecondition, before the CA key is loaded.
36+
func TestClockGateRefusesSigningWhileUnsynced(t *testing.T) {
37+
f := newSignerFixture(t)
38+
cfg := caProfileConfig(config.RoleIssuing)
39+
loaded := false
40+
load, issuer, get := f.loaders(cfg, new(bool))
41+
wrapped := func(ctx context.Context) (crypto.Signer, func(), error) {
42+
loaded = true
43+
return load(ctx)
44+
}
45+
s := NewCASigner(wrapped, issuer, get).WithClockGate(func() bool { return false })
46+
47+
_, err := s.IssueLeaf(context.Background(), makeCSR(t, "node.example"), "leaf-server")
48+
wantCode(t, err, codes.FailedPrecondition)
49+
if !strings.Contains(status.Convert(err).Message(), "allow_unsynced_clock") {
50+
t.Fatalf("refusal %q does not name the override", err)
51+
}
52+
_, _, err = s.IssueLeafForNames(context.Background(), makeCSR(t, "node.example"), "leaf-server", []string{"node.example"})
53+
wantCode(t, err, codes.FailedPrecondition)
54+
_, _, err = s.IssueLeafWithRequestSANs(context.Background(), makeCSR(t, "node.example"), "leaf-server", nil)
55+
wantCode(t, err, codes.FailedPrecondition)
56+
57+
sub := NewCASigner(wrapped, issuer, func(context.Context) (*config.Config, error) {
58+
return caProfileConfig(config.RoleIntermediate), nil
59+
}).WithClockGate(func() bool { return false })
60+
_, _, _, err = sub.SignSubordinate(context.Background(), makeCSR(t, "Child CA"), "sub-ca")
61+
wantCode(t, err, codes.FailedPrecondition)
62+
63+
if loaded {
64+
t.Fatal("the CA key was loaded although the clock gate refused")
65+
}
66+
}
67+
68+
func TestClockGateAllowsSigningOnceSynced(t *testing.T) {
69+
f := newSignerFixture(t)
70+
load, issuer, get := f.loaders(caProfileConfig(config.RoleIssuing), new(bool))
71+
s := NewCASigner(load, issuer, get).WithClockGate(func() bool { return true })
72+
if _, err := s.IssueLeaf(context.Background(), makeCSR(t, "node.example"), "leaf-server"); err != nil {
73+
t.Fatalf("IssueLeaf with a synced clock: %v", err)
74+
}
75+
}
76+
77+
func TestClockGateOverrideAllowsSigningWhileUnsynced(t *testing.T) {
78+
f := newSignerFixture(t)
79+
cfg := caProfileConfig(config.RoleIntermediate)
80+
cfg.PKI.AllowUnsyncedClock = true
81+
load, issuer, get := f.loaders(cfg, new(bool))
82+
s := NewCASigner(load, issuer, get).WithClockGate(func() bool { return false })
83+
if _, _, _, err := s.SignSubordinate(context.Background(), makeCSR(t, "Child CA"), "sub-ca"); err != nil {
84+
t.Fatalf("SignSubordinate with allow_unsynced_clock: %v", err)
85+
}
86+
}
87+
88+
// With no time source the node wires no gate (or one that always passes), so
89+
// signing is never gated.
90+
func TestNoClockGateNeverGates(t *testing.T) {
91+
f := newSignerFixture(t)
92+
load, issuer, get := f.loaders(caProfileConfig(config.RoleIssuing), new(bool))
93+
s := NewCASigner(load, issuer, get)
94+
if _, err := s.IssueLeaf(context.Background(), makeCSR(t, "node.example"), "leaf-server"); err != nil {
95+
t.Fatalf("IssueLeaf with no clock gate: %v", err)
96+
}
97+
}
98+
99+
// Every certificate the signer returns reports its notBefore, so the clock
100+
// floor can be raised past it.
101+
func TestIssuedHookSeesEveryNotBefore(t *testing.T) {
102+
f := newSignerFixture(t)
103+
load, issuer, get := f.loaders(caProfileConfig(config.RoleIssuing), new(bool))
104+
var seen []time.Time
105+
s := NewCASigner(load, issuer, get).WithIssuedHook(func(nb time.Time) { seen = append(seen, nb) })
106+
before := time.Now().Add(-time.Second)
107+
if _, err := s.IssueLeaf(context.Background(), makeCSR(t, "node.example"), "leaf-server"); err != nil {
108+
t.Fatal(err)
109+
}
110+
if len(seen) != 1 || seen[0].Before(before) {
111+
t.Fatalf("issued hook saw %v", seen)
112+
}
113+
}

0 commit comments

Comments
 (0)