ЛР7: включить internal/secrets и vendor data в чистый clone
This commit is contained in:
+4
-2
@@ -3,10 +3,9 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets
|
||||
certs
|
||||
volumes
|
||||
data
|
||||
/data
|
||||
backups
|
||||
*.key
|
||||
*.pem
|
||||
@@ -14,6 +13,9 @@ backups
|
||||
*.pfx
|
||||
*.jks
|
||||
.venv
|
||||
.local-secrets
|
||||
.scratch
|
||||
.tools
|
||||
__pycache__
|
||||
node_modules
|
||||
evidence
|
||||
|
||||
+1
-3
@@ -2,7 +2,6 @@
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
secrets/
|
||||
certs/private/
|
||||
*.key
|
||||
*.p12
|
||||
@@ -33,8 +32,7 @@ coverage/
|
||||
|
||||
# Lab7 local operator material: CAs, leaf keys, passwords, DSNs, OpenBao
|
||||
# init shares, AppRole secret-ids and rendered provisioning containing keys.
|
||||
.local-secrets/
|
||||
.scratch/
|
||||
.local-.scratch/
|
||||
|
||||
# Local tooling and virtualenv
|
||||
.tools/
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend t
|
||||
bind :8443 ssl crt /run/secrets/lb_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
|
||||
http-request deny unless { ssl_c_s_dn(CN) -m str lab7-lb } { method GET } { path_beg /ok }
|
||||
http-request return status 200 content-type text/plain string ok
|
||||
@@ -0,0 +1,13 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend t
|
||||
bind :8443 ssl crt /run/secrets/lb_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
|
||||
http-request deny unless { ssl_c_s_dn(CN) -m str lab7-bootstrap } || { ssl_c_s_dn(CN) -m str lab7-api } || { ssl_c_s_dn(CN) -m str lab7-worker }
|
||||
http-request allow if { method GET } { path /messenger-attachments/ }
|
||||
http-request return status 403 content-type text/plain string denied
|
||||
http-request return status 200 content-type text/plain string allowed
|
||||
@@ -0,0 +1,11 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend mtls
|
||||
bind :8443 ssl crt /certs/server.pem ca-file /certs/service-ca.crt verify required crl-file /certs/service-ca.crl.pem
|
||||
http-request deny status 403 unless { ssl_c_s_dn(CN) -m str lab7-lb }
|
||||
http-request return status 200 content-type text/plain string ok
|
||||
@@ -0,0 +1,12 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend t
|
||||
bind :8443 ssl crt /run/secrets/lb_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
|
||||
http-request allow if { ssl_c_s_dn(CN) -m str lab7-api } { method GET } { path /messenger-attachments/ } { url_param(prefix) -m beg staging }
|
||||
http-request return status 403 content-type text/plain string denied
|
||||
http-request return status 200 content-type text/plain string allowed
|
||||
@@ -0,0 +1,12 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend t
|
||||
bind :8443 ssl crt /run/secrets/lb_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
|
||||
http-request allow if { ssl_c_s_dn(CN) -m str lab7-api } { method GET } { path /messenger-attachments/ }
|
||||
http-request return status 403 content-type text/plain string denied
|
||||
http-request return status 200 content-type text/plain string allowed
|
||||
@@ -0,0 +1,11 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend t
|
||||
bind :8443 ssl crt /run/secrets/lb_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
|
||||
http-request set-header X-Prefix %[url_param(prefix)]
|
||||
http-request return status 200 content-type text/plain lf-string "prefix=%[url_param(prefix)] query=%[query] path=%[path]"
|
||||
@@ -0,0 +1,12 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
defaults
|
||||
mode http
|
||||
timeout connect 2s
|
||||
timeout client 5s
|
||||
timeout server 5s
|
||||
frontend t
|
||||
bind :8443 ssl crt /run/secrets/lb_server_bundle ca-file /run/secrets/service_ca verify required crl-file /run/secrets/service_ca_crl
|
||||
http-request allow if { ssl_c_s_dn(CN) -m str lab7-api } { method GET } { path /messenger-attachments/ } { query -m sub prefix=staging }
|
||||
http-request return status 403 content-type text/plain string denied
|
||||
http-request return status 200 content-type text/plain string allowed
|
||||
@@ -0,0 +1,12 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBvjCCAWWgAwIBAgIQdqoBZgGwnwUylCPse1Ey2TAKBggqhkjOPQQDAjA/MSMw
|
||||
IQYDVQQKExpNVFVTSSBsYWI3IHN5bnRoZXRpYyBzdGFuZDEYMBYGA1UEAxMPbGFi
|
||||
Ny1zZXJ2aWNlLWNhMB4XDTI2MTIwNjEzNTQzNVoXDTI3MDEwNTEzNTYzNVowOjEj
|
||||
MCEGA1UEChMaTVRVU0kgbGFiNyBzeW50aGV0aWMgc3RhbmQxEzARBgNVBAMTCmxh
|
||||
Yjctcm9ndWUwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASFNE8LaDE0ecwFvvAu
|
||||
6AXzL/u9Ip2uKQQZs3CG3/IZCrqhFqCSNuCCYeG5kiqro8vsv7qsAFRUW+mj8exz
|
||||
ZERYo0gwRjAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHwYD
|
||||
VR0jBBgwFoAUdOM4cWkac4e90SEGQISp+VorBK8wCgYIKoZIzj0EAwIDRwAwRAIg
|
||||
NKWWxfZ2FKfsssRliUUtM3otm/KFLhPwH6+l0wcx71sCIFQtE56J12JAhZBO1evI
|
||||
nqHbjNP0+CJiYho9gred3/Ly
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,12 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBuzCCAWGgAwIBAgIQHC4V1OWlGxyUD9S00cgsZzAKBggqhkjOPQQDAjA8MSMw
|
||||
IQYDVQQKExpNVFVTSSBsYWI3IHN5bnRoZXRpYyBzdGFuZDEVMBMGA1UEAxMMbGFi
|
||||
Ny1lZGdlLWNhMB4XDTI2MTIwNjEzNTEzNVoXDTM2MTIwMzEzNTYzNVowPDEjMCEG
|
||||
A1UEChMaTVRVU0kgbGFiNyBzeW50aGV0aWMgc3RhbmQxFTATBgNVBAMTDGxhYjct
|
||||
ZWRnZS1jYTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABADBTPpIFgTIKhfPLxyj
|
||||
xP3s6cyNv0DW21l55WZp1M6Vn6zxyqdz2FYrzSbViHm02hl4Ka4xJyB8ux6Pkx+M
|
||||
ciOjRTBDMA4GA1UdDwEB/wQEAwIBhjASBgNVHRMBAf8ECDAGAQH/AgEAMB0GA1Ud
|
||||
DgQWBBRb4+2/xo5gLcH4w51MKKJsjB7I0DAKBggqhkjOPQQDAgNIADBFAiADNw/7
|
||||
J7/ikYxoF6xLWGm8L1+A8IooPLKVs4A8iGhMeAIhALjv/hgj+ph12aLvQOE57cx6
|
||||
TjFCzluTVRjeDgSxovg9
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,12 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBvTCCAWKgAwIBAgIQM9KDQCC3bwMDjNu9bcMRvjAKBggqhkjOPQQDAjA/MSMw
|
||||
IQYDVQQKExpNVFVTSSBsYWI3IHN5bnRoZXRpYyBzdGFuZDEYMBYGA1UEAxMPbGFi
|
||||
Ny1zZXJ2aWNlLWNhMB4XDTI2MTIwNjEzNTQzNVoXDTI3MDEwNTEzNTYzNVowNzEj
|
||||
MCEGA1UEChMaTVRVU0kgbGFiNyBzeW50aGV0aWMgc3RhbmQxEDAOBgNVBAMTB2xh
|
||||
YjctbGIwWTATBgcqhkjOPQIBBggqhkjOPQMBBwNCAASqZHVRyiy7CM6Tmwc4HRJW
|
||||
ZS1EVACCkX5MSib2wsPevl0/EopuJuJ60f9e4pmVn2Dr2OhmOYVzjVGTp49rZGcJ
|
||||
o0gwRjAOBgNVHQ8BAf8EBAMCB4AwEwYDVR0lBAwwCgYIKwYBBQUHAwIwHwYDVR0j
|
||||
BBgwFoAUdOM4cWkac4e90SEGQISp+VorBK8wCgYIKoZIzj0EAwIDSQAwRgIhAPow
|
||||
QUICBhkq1OkklF2ILJu4OR8iDmlQyT4uEK7CLLy5AiEAlwbkx+H3VKQU8e+n3IHt
|
||||
JKCwOAvBXiN114IkS1Eu4v4=
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,56 @@
|
||||
{
|
||||
"next_crl_number": 2,
|
||||
"issued": [
|
||||
{
|
||||
"serial": "55510699454407161057684509678035116950",
|
||||
"ca": "service",
|
||||
"cn": "api",
|
||||
"profile": "server",
|
||||
"sans": [
|
||||
"api"
|
||||
],
|
||||
"not_before": "2026-12-06T13:54:35Z",
|
||||
"not_after": "2027-01-05T13:56:35Z",
|
||||
"cert_file": "server.crt",
|
||||
"key_file": "server.key",
|
||||
"revoked_at": "0001-01-01T00:00:00Z"
|
||||
},
|
||||
{
|
||||
"serial": "68883672201708780579376878355566760382",
|
||||
"ca": "service",
|
||||
"cn": "lab7-lb",
|
||||
"profile": "client",
|
||||
"sans": null,
|
||||
"not_before": "2026-12-06T13:54:35Z",
|
||||
"not_after": "2027-01-05T13:56:35Z",
|
||||
"cert_file": "good.crt",
|
||||
"key_file": "good.key",
|
||||
"revoked_at": "0001-01-01T00:00:00Z"
|
||||
},
|
||||
{
|
||||
"serial": "157731622332776180712354869920429847257",
|
||||
"ca": "service",
|
||||
"cn": "lab7-rogue",
|
||||
"profile": "client",
|
||||
"sans": null,
|
||||
"not_before": "2026-12-06T13:54:35Z",
|
||||
"not_after": "2027-01-05T13:56:35Z",
|
||||
"cert_file": "bad.crt",
|
||||
"key_file": "bad.key",
|
||||
"revoked_at": "0001-01-01T00:00:00Z"
|
||||
},
|
||||
{
|
||||
"serial": "240781216131885218444784897140404811881",
|
||||
"ca": "service",
|
||||
"cn": "lab7-lb",
|
||||
"profile": "client",
|
||||
"sans": null,
|
||||
"not_before": "2026-12-06T13:54:35Z",
|
||||
"not_after": "2027-01-05T13:56:35Z",
|
||||
"cert_file": "rev.crt",
|
||||
"key_file": "rev.key",
|
||||
"revoked_at": "2026-12-06T13:56:35Z",
|
||||
"revoke_reason": "keyCompromise"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBvjCCAWOgAwIBAgIRALUkxoHjY8OJg2wIsJm8eGkwCgYIKoZIzj0EAwIwPzEj
|
||||
MCEGA1UEChMaTVRVU0kgbGFiNyBzeW50aGV0aWMgc3RhbmQxGDAWBgNVBAMTD2xh
|
||||
Yjctc2VydmljZS1jYTAeFw0yNjEyMDYxMzU0MzVaFw0yNzAxMDUxMzU2MzVaMDcx
|
||||
IzAhBgNVBAoTGk1UVVNJIGxhYjcgc3ludGhldGljIHN0YW5kMRAwDgYDVQQDEwds
|
||||
YWI3LWxiMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEHG0n92l4csrhKTUwBe+K
|
||||
EImPhMYW6fcRnc05SCQEc5ccRmq8qUnykBXXo25x/Cru6+DoQajftcZLKR3wicr0
|
||||
wKNIMEYwDgYDVR0PAQH/BAQDAgeAMBMGA1UdJQQMMAoGCCsGAQUFBwMCMB8GA1Ud
|
||||
IwQYMBaAFHTjOHFpGnOHvdEhBkCEqflaKwSvMAoGCCqGSM49BAMCA0kAMEYCIQDw
|
||||
/yqAmcWEgf6cqNz0WW0R6uyUG9OFZCb9n45SNpttwQIhAOev+XTvLDhMMIQUgl6C
|
||||
snDOwY21HEWoaC72JSwrNQzs
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,12 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIByDCCAW6gAwIBAgIQKcL4ye/XiN2NojglW32jljAKBggqhkjOPQQDAjA/MSMw
|
||||
IQYDVQQKExpNVFVTSSBsYWI3IHN5bnRoZXRpYyBzdGFuZDEYMBYGA1UEAxMPbGFi
|
||||
Ny1zZXJ2aWNlLWNhMB4XDTI2MTIwNjEzNTQzNVoXDTI3MDEwNTEzNTYzNVowMzEj
|
||||
MCEGA1UEChMaTVRVU0kgbGFiNyBzeW50aGV0aWMgc3RhbmQxDDAKBgNVBAMTA2Fw
|
||||
aTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABEvSrblSZpqzzEu/ksBA2te/rBjG
|
||||
Yms4vL4ubIfjBkBQT+1KS13g0fCsWByZ/AljJIZKIS32Y1n0jJ3w3mgX3/6jWDBW
|
||||
MA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDATAfBgNVHSMEGDAW
|
||||
gBR04zhxaRpzh73RIQZAhKn5WisErzAOBgNVHREEBzAFggNhcGkwCgYIKoZIzj0E
|
||||
AwIDSAAwRQIhAKcgz0FUAwTmCEZ97lGYqQJnKPYVEfcEqoLIo7fh/ogrAiAXDr2C
|
||||
8K7pfbk3BPQ6gaT7+JDvpfWyYLa2J/tg6e0Thg==
|
||||
-----END CERTIFICATE-----
|
||||
Binary file not shown.
@@ -0,0 +1,12 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIBwjCCAWegAwIBAgIQEL1dkkD7pfa45YAHZVrc1DAKBggqhkjOPQQDAjA/MSMw
|
||||
IQYDVQQKExpNVFVTSSBsYWI3IHN5bnRoZXRpYyBzdGFuZDEYMBYGA1UEAxMPbGFi
|
||||
Ny1zZXJ2aWNlLWNhMB4XDTI2MTIwNjEzNTEzNVoXDTM2MTIwMzEzNTYzNVowPzEj
|
||||
MCEGA1UEChMaTVRVU0kgbGFiNyBzeW50aGV0aWMgc3RhbmQxGDAWBgNVBAMTD2xh
|
||||
Yjctc2VydmljZS1jYTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABKwmKmrgvOJf
|
||||
7F2z0AFypEi7jVG953L0e25o3K5A2feKtia/m+YoS0LIn13cHoM10AYVIGIHlNVi
|
||||
U5DWt9vIBrCjRTBDMA4GA1UdDwEB/wQEAwIBhjASBgNVHRMBAf8ECDAGAQH/AgEA
|
||||
MB0GA1UdDgQWBBR04zhxaRpzh73RIQZAhKn5WisErzAKBggqhkjOPQQDAgNJADBG
|
||||
AiEA2GPJlFEmPvrOA5q2WRglgp5WU0Crs+654qtp/05BSZ4CIQCIynep8Q3f+gDj
|
||||
JQgO+ARuyqjuhMxfJxyjA+bZO9KavQ==
|
||||
-----END CERTIFICATE-----
|
||||
@@ -0,0 +1,15 @@
|
||||
import socket, ssl, sys
|
||||
host='session-gw'; port=6379
|
||||
ctx=ssl.create_default_context(cafile='/pki/service-ca.crt')
|
||||
ctx.load_cert_chain('/pki/api-client.crt','/pki/api-client.key')
|
||||
s=ctx.wrap_socket(socket.create_connection((host,port),5),server_hostname=host)
|
||||
password=open('/sec/valkey_session_password').read().strip().encode()
|
||||
def cmd(*parts):
|
||||
out=f'*{len(parts)}\r\n'.encode()
|
||||
for p in parts:
|
||||
p=p if isinstance(p,bytes) else p.encode()
|
||||
out+=f'${len(p)}\r\n'.encode()+p+b'\r\n'
|
||||
s.sendall(out)
|
||||
return s.recv(4096)
|
||||
print('AUTH:',cmd('AUTH','session',password))
|
||||
print('PING:',cmd('PING'))
|
||||
@@ -0,0 +1,329 @@
|
||||
// Package secrets implements the small OpenBao client used by the API and the
|
||||
// worker: AppRole login, one scoped KV v2 read at startup and periodic
|
||||
// token renewal.
|
||||
//
|
||||
// The application never receives an OpenBao root token, an unseal share or a
|
||||
// long-lived global token. role-id and secret-id are files produced by the
|
||||
// operator bootstrap; the secret-id has a bounded TTL and the issued service
|
||||
// token is renewable with a bounded max TTL. Neither the secret-id nor the
|
||||
// token is logged.
|
||||
package secrets
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Config describes one service identity.
|
||||
type Config struct {
|
||||
Address string
|
||||
CACertFile string
|
||||
RoleIDFile string
|
||||
SecretIDFile string
|
||||
SecretPath string
|
||||
Timeout time.Duration
|
||||
}
|
||||
|
||||
// Client owns the renewable OpenBao token of one process.
|
||||
type Client struct {
|
||||
address string
|
||||
secretPath string
|
||||
http *http.Client
|
||||
roleID string
|
||||
secretID string
|
||||
|
||||
mu sync.Mutex
|
||||
token string
|
||||
expiresAt time.Time
|
||||
lastTTL time.Duration
|
||||
}
|
||||
|
||||
type loginResponse struct {
|
||||
Auth struct {
|
||||
ClientToken string `json:"client_token"`
|
||||
LeaseDuration int `json:"lease_duration"`
|
||||
} `json:"auth"`
|
||||
}
|
||||
|
||||
type kvResponse struct {
|
||||
Data struct {
|
||||
Data map[string]any `json:"data"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// Fetch logs in with AppRole, reads exactly one scoped KV v2 document and
|
||||
// returns its string fields. Login is retried until the context deadline so a
|
||||
// starting OpenBao does not make the service crash-loop immediately.
|
||||
func Fetch(ctx context.Context, cfg Config) (map[string]string, *Client, error) {
|
||||
if strings.TrimSpace(cfg.Address) == "" {
|
||||
return nil, nil, errors.New("OpenBao address is required")
|
||||
}
|
||||
if cfg.Timeout <= 0 {
|
||||
cfg.Timeout = 30 * time.Second
|
||||
}
|
||||
roleID, err := readCredential(cfg.RoleIDFile, "role-id")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
secretID, err := readCredential(cfg.SecretIDFile, "secret-id")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
httpClient, err := tlsHTTPClient(cfg.CACertFile, cfg.Address)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
client := &Client{
|
||||
address: strings.TrimRight(cfg.Address, "/"),
|
||||
secretPath: strings.TrimLeft(cfg.SecretPath, "/"),
|
||||
http: httpClient,
|
||||
roleID: roleID,
|
||||
secretID: secretID,
|
||||
}
|
||||
|
||||
deadline := time.Now().Add(cfg.Timeout)
|
||||
var lastErr error
|
||||
for {
|
||||
loginCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
|
||||
lastErr = client.login(loginCtx)
|
||||
cancel()
|
||||
if lastErr == nil {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
return nil, nil, fmt.Errorf("OpenBao AppRole login failed within %s: %w", cfg.Timeout, lastErr)
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil, nil, ctx.Err()
|
||||
case <-time.After(time.Second):
|
||||
}
|
||||
}
|
||||
|
||||
readCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
values, err := client.readSecret(readCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return values, client, nil
|
||||
}
|
||||
|
||||
// TTL returns the last lease duration reported by OpenBao. It is used by the
|
||||
// startup log and the sealed-OpenBao evidence; it is not secret.
|
||||
func (c *Client) TTL() time.Duration {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
return c.lastTTL
|
||||
}
|
||||
|
||||
// RunRenewal renews the service token before expiry. If renewal fails it
|
||||
// re-authenticates with the same bounded secret-id. A sealed OpenBao therefore
|
||||
// makes future renewal/restart impossible, but a running process keeps using
|
||||
// the connections and secrets it already obtained; this is the documented
|
||||
// bounded behaviour, not a plaintext fallback.
|
||||
func (c *Client) RunRenewal(ctx context.Context, logger *slog.Logger) {
|
||||
for {
|
||||
c.mu.Lock()
|
||||
ttl := c.lastTTL
|
||||
c.mu.Unlock()
|
||||
wait := ttl / 3
|
||||
if wait < 10*time.Second {
|
||||
wait = 10 * time.Second
|
||||
}
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(wait):
|
||||
}
|
||||
|
||||
renewCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err := c.renew(renewCtx)
|
||||
cancel()
|
||||
if err == nil {
|
||||
logger.Debug("OpenBao service token renewed")
|
||||
continue
|
||||
}
|
||||
logger.Warn("OpenBao token renewal failed; retrying AppRole login", "error", err)
|
||||
|
||||
loginCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
|
||||
err = c.login(loginCtx)
|
||||
cancel()
|
||||
if err != nil {
|
||||
// Do not exit: the process still has its in-memory credentials and
|
||||
// established database/broker connections. A restart will fail
|
||||
// readiness until an operator unseals OpenBao and reissues the
|
||||
// AppRole secret-id if its TTL also expired.
|
||||
logger.Error("OpenBao AppRole re-authentication failed; continuing with existing credentials", "error", err)
|
||||
continue
|
||||
}
|
||||
logger.Info("OpenBao AppRole re-authentication succeeded")
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Client) login(ctx context.Context) error {
|
||||
body, err := json.Marshal(map[string]string{"role_id": c.roleID, "secret_id": c.secretID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.address+"/v1/auth/approle/login", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
response, err := c.http.Do(request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("OpenBao login request failed: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("OpenBao login rejected with status %d", response.StatusCode)
|
||||
}
|
||||
var decoded loginResponse
|
||||
if err := json.Unmarshal(payload, &decoded); err != nil || decoded.Auth.ClientToken == "" {
|
||||
return errors.New("OpenBao login returned no token")
|
||||
}
|
||||
ttl := time.Duration(decoded.Auth.LeaseDuration) * time.Second
|
||||
c.mu.Lock()
|
||||
c.token = decoded.Auth.ClientToken
|
||||
c.lastTTL = ttl
|
||||
c.expiresAt = time.Now().Add(ttl)
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) renew(ctx context.Context) error {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodPost, c.address+"/v1/auth/token/renew-self", nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.mu.Lock()
|
||||
token := c.token
|
||||
c.mu.Unlock()
|
||||
request.Header.Set("X-Vault-Token", token)
|
||||
response, err := c.http.Do(request)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return fmt.Errorf("OpenBao renewal rejected with status %d", response.StatusCode)
|
||||
}
|
||||
var decoded loginResponse
|
||||
if err := json.Unmarshal(payload, &decoded); err != nil {
|
||||
return err
|
||||
}
|
||||
ttl := time.Duration(decoded.Auth.LeaseDuration) * time.Second
|
||||
c.mu.Lock()
|
||||
c.lastTTL = ttl
|
||||
c.expiresAt = time.Now().Add(ttl)
|
||||
c.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *Client) readSecret(ctx context.Context) (map[string]string, error) {
|
||||
request, err := http.NewRequestWithContext(ctx, http.MethodGet, c.address+"/v1/"+c.secretPath, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.mu.Lock()
|
||||
token := c.token
|
||||
c.mu.Unlock()
|
||||
request.Header.Set("X-Vault-Token", token)
|
||||
response, err := c.http.Do(request)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("OpenBao secret read failed: %w", err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
payload, err := io.ReadAll(io.LimitReader(response.Body, 1<<20))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if response.StatusCode != http.StatusOK {
|
||||
return nil, fmt.Errorf("OpenBao secret read rejected with status %d", response.StatusCode)
|
||||
}
|
||||
var decoded kvResponse
|
||||
if err := json.Unmarshal(payload, &decoded); err != nil {
|
||||
return nil, errors.New("OpenBao secret document is not valid JSON")
|
||||
}
|
||||
if decoded.Data.Data == nil {
|
||||
return nil, errors.New("OpenBao secret document has no data")
|
||||
}
|
||||
values := make(map[string]string, len(decoded.Data.Data))
|
||||
for key, raw := range decoded.Data.Data {
|
||||
if text, ok := raw.(string); ok {
|
||||
values[key] = text
|
||||
}
|
||||
}
|
||||
return values, nil
|
||||
}
|
||||
|
||||
func readCredential(path, label string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("OpenBao %s file path is required", label)
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("OpenBao %s file is not readable (run make env/bootstrap): %w", label, err)
|
||||
}
|
||||
value := strings.TrimSpace(string(data))
|
||||
if value == "" {
|
||||
return "", fmt.Errorf("OpenBao %s file is empty", label)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
func tlsHTTPClient(caFile, address string) (*http.Client, error) {
|
||||
if strings.TrimSpace(caFile) == "" {
|
||||
return nil, errors.New("OpenBao CA certificate file is required")
|
||||
}
|
||||
pemData, err := os.ReadFile(caFile)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read OpenBao CA certificate: %w", err)
|
||||
}
|
||||
pool := x509.NewCertPool()
|
||||
if !pool.AppendCertsFromPEM(pemData) {
|
||||
return nil, errors.New("OpenBao CA certificate file contains no certificates")
|
||||
}
|
||||
parsed, err := url.Parse(address)
|
||||
if err != nil || parsed.Host == "" {
|
||||
return nil, errors.New("OpenBao address is not a valid URL")
|
||||
}
|
||||
tlsConfig := &tls.Config{
|
||||
RootCAs: pool,
|
||||
ServerName: parsed.Hostname(),
|
||||
MinVersion: tls.VersionTLS12,
|
||||
}
|
||||
return &http.Client{
|
||||
Timeout: 10 * time.Second,
|
||||
Transport: &http.Transport{
|
||||
TLSClientConfig: tlsConfig,
|
||||
ForceAttemptHTTP2: false,
|
||||
MaxIdleConns: 4,
|
||||
IdleConnTimeout: 30 * time.Second,
|
||||
TLSHandshakeTimeout: 5 * time.Second,
|
||||
},
|
||||
CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user