Kiến thức chung · Advanced · Không phụ thuộc ngôn ngữ

Kết nối, TLS và mTLS trong CoAkka Runtime

Network mode quyết định process có nhận kết nối hay không. Connection strategy quyết định Core mở và tái sử dụng connection thế nào. TLS/mTLS bảo vệ chính đường truyền đó. Ba quyết định liên quan nhưng không thay thế nhau.

01 · Mô hình chung

Cấu hình từng trục theo câu hỏi nó trả lời

Network mode

Process này chỉ xử lý local, chỉ gọi ra ngoài hay còn nhận kết nối từ peer? Chọn EMBEDDED, OUTBOUND_ONLY hoặc NETWORK_NODE.

Connection strategy

Mỗi exchange mở connection mới hay Core giữ một tập connection có bound để tái sử dụng? Đây là startup policy của từng CoAkka Runtime instance.

Transport security

Đường TCP dùng plaintext, xác thực server bằng TLS hay xác thực hai phía bằng mTLS? Security mode độc lập với strategy.

Với startup contract hiện tại, bỏ trống connection group để Core chọn MULTIPLEXED; bỏ trống security group giữ PLAINTEXT. Đây là effective default do Core publish, không phải bảng default của connector. Frozen legacy constructor riêng vẫn giữ PER_EXCHANGE + PLAINTEXT. Hãy đọc startup configuration và capability hiệu lực của đúng native artifact; tên edition hoặc package không thay cho capability evidence.

02 · Connection strategy

Giữ multiplexing mặc định; chỉ chọn mode khác khi workload cần

Per exchange

Mở, gửi một request, nhận một terminal result rồi đóng. Một exchange trên mỗi connection. Đây là baseline rõ ràng và là legacy-constructor default, không phải omitted-input default hiện tại.

Bounded pool

Mượn và tái sử dụng một trong số connection được giữ có bound. Mỗi connection vẫn chỉ xử lý một exchange tại một thời điểm.

Persistent single-flight

Giữ tối đa một connection cho đúng endpoint và serialize các exchange. Chỉ dùng khi capability tương ứng có hiệu lực.

Multiplexed

Giữ connection và correlate nhiều stream đồng thời trong bound. Đây là omitted-input default của startup contract hiện tại; giới hạn hiện tại là 16 stream trên một connection.

Bounded pool defaults revision 1 giữ tối đa 8 connection, retire sau 1024 request và idle timeout 30 giây. Chỉ override tuning khi artifact công bố capability tuning và đo đạc cho thấy default chưa phù hợp.

03 · Trust boundary

Đặt TLS/mTLS ở nơi identity thực sự được kiểm tra

Plaintext

Không mã hóa và không xác thực peer bằng certificate. Chỉ phù hợp khi boundary bên ngoài đã được chọn và chấp nhận rõ ràng.

TLS

Mã hóa traffic và phía outbound xác thực certificate cùng host identity của receiver.

Mutual TLS

Thêm client certificate để receiver cũng xác thực identity của phía gọi.

CoAkka Runtime TLS bảo vệ built-in public TCP path với TLS 1.2 tối thiểu; TLS 1.3 có thể được negotiate. Public ingress TLS vẫn thuộc gateway hoặc ingress. Certificate issuance, secret distribution, firewall/CNI/DNS, authorization và clock readiness vẫn thuộc platform hoặc app-host. Runtime TLS/mTLS cho traffic giữa các CoAkka participant không cần một service-mesh sidecar, nhưng một tổ chức vẫn có thể chọn mesh cho traffic không phải CoAkka hay policy proxy tập trung.

Trên edge, LAN hoặc private VLAN, địa chỉ riêng không tự chứng minh confidentiality hay peer identity. Đừng bật certificate validation trước khi host có wall clock đáng tin cậy.

Xem mTLS và quyền người dùng qua ví dụ xem đơn hàng.

04 · Credential lifecycle

Platform cấp credential; Core publish immutable context

mode
PLAINTEXT, TLS hoặc MUTUAL_TLS.
credential_generation
Generation dương lúc đầu; reload đang chạy phải tăng nghiêm ngặt.
credential_id
Operator label không chứa secret, tối đa 127 byte.
ca_certificate_file
PEM trust roots dùng để xác thực peer.
identity_certificate_file
PEM identity certificate chain của process.
private_key_file
PEM private key tương ứng; quyền file phải được giới hạn.
GRACEFUL
Generation mới áp dụng cho handshake mới; session cũ hoàn tất trên generation đã giữ.
DRAIN_EXISTING_CONNECTIONS
Thêm bounded retirement cho session cũ mà không ngắt request đang in-flight.
  1. Platform hoặc secret tooling ghi bộ file mới một cách atomic.
  2. App control flow gửi cùng TLS/mTLS mode với generation cao hơn; không reload trong request handler nhạy latency.
  3. Core tải và validate toàn bộ candidate trước khi publish một immutable context mới.
  4. App kiểm tra structured result rồi mới retire secret cũ theo deployment policy.

Path chỉ được mượn trong synchronous apply. Public snapshot không trả path, PEM, private key hay raw TLS diagnostics. Core không tạo thread để poll file và không tự renew certificate.

05 · Projection theo ngôn ngữ · Go trước

Go: network node + bounded pool + mTLS + reload

Sample này dành cho deployment nâng cao, không phải bài Beginner. Nó cần connector v3.3.2, một native profile có đủ capability, DNS/advertise name khớp certificate SAN và hai bộ secret đã mount. Copy file vào IDE rồi thay identity, endpoint và secret path theo nền tảng đang triển khai.

ReadRuntimeCapabilities
Đọc sự thật từ native artifact đã load; sample fail closed nếu thiếu bounded pool, mTLS hoặc credential reload.
NetworkNode
Bind trên mọi interface tại port 19301 nhưng advertise một DNS name cụ thể mà peer và certificate cùng nhận biết.
ConnectionStrategy
Chọn bounded pool và để Core dùng default có provenance thay vì copy tuning table vào app.
Security
Generation 1 được apply khi host còn CREATED; startup bị từ chối sẽ giải phóng handle.
TCPConnectionConfig / TCPSecurityInfo
Đọc cấu hình Core thực sự chấp nhận thay vì suy từ input.
ApplyTCPSecurity
Gửi generation 2 cùng mTLS mode; result cho biết generation nào vẫn đang active nếu candidate bị từ chối.
connectivity.go
package main

import (
	"errors"
	"fmt"
	"os"

	coakka "github.com/phuong-tran/coakka-runtime-go/v3"
)

func run() (err error) {
	capabilities, err := coakka.ReadRuntimeCapabilities("")
	if err != nil {
		return fmt.Errorf("read CoAkka Runtime capabilities: %w", err)
	}
	required := coakka.RuntimeCapabilityTCPBoundedPool |
		coakka.RuntimeCapabilityTCPMutualTLS |
		coakka.RuntimeCapabilityTLSCredentialReload
	if !capabilities.Supports(required) {
		return errors.New("loaded CoAkka Runtime profile does not provide bounded pool, mTLS and credential reload")
	}

	security := coakka.RuntimeTCPSecuritySpec{
		Mode:                    coakka.RuntimeTCPSecurityMutualTLS,
		ReloadMode:              coakka.RuntimeTLSReloadGraceful,
		CredentialGeneration:    1,
		CredentialID:            "orders-2026-11-a",
		CACertificateFile:       "/run/secrets/coakka/ca.pem",
		IdentityCertificateFile: "/run/secrets/coakka/tls.crt",
		PrivateKeyFile:          "/run/secrets/coakka/tls.key",
	}
	host, err := coakka.StartRuntimeHost(coakka.ConnectorStartSpec{
		SystemName: "orders",
		NodeID:     "orders-0",
		Routes:     []coakka.RouteSpec{coakka.LocalRouteDefault("orders.quote")},
		Network: coakka.NetworkNode(
			"0.0.0.0", 19301,
			"orders-0.orders.default.svc.cluster.local", 19301,
		),
		ConnectionStrategy: &coakka.RuntimeTCPConnectionStrategySpec{
			Mode: coakka.RuntimeTCPConnectionBoundedPool,
		},
		Security: &security,
	}, "")
	if err != nil {
		return fmt.Errorf("start secure CoAkka Runtime node: %w", err)
	}
	defer func() {
		err = errors.Join(err, host.Close())
	}()

	connection, err := host.TCPConnectionConfig()
	if err != nil {
		return fmt.Errorf("read effective connection strategy: %w", err)
	}
	activeSecurity, err := host.TCPSecurityInfo()
	if err != nil {
		return fmt.Errorf("read effective transport security: %w", err)
	}
	fmt.Printf("connection_mode=%d security_mode=%d credential_generation=%d\n",
		connection.Mode, activeSecurity.Mode, activeSecurity.CredentialGeneration)

	nextSecurity := security
	nextSecurity.CredentialGeneration = 2
	nextSecurity.CredentialID = "orders-2026-11-b"
	nextSecurity.IdentityCertificateFile = "/run/secrets/coakka-next/tls.crt"
	nextSecurity.PrivateKeyFile = "/run/secrets/coakka-next/tls.key"

	result, err := host.ApplyTCPSecurity(nextSecurity)
	if err != nil {
		return fmt.Errorf("submit credential generation 2: %w", err)
	}
	if !result.Applied() {
		return fmt.Errorf("credential reload rejected: %s; active generation=%d",
			result.ReasonName, result.ActiveSecurity.CredentialGeneration)
	}
	fmt.Printf("credential_generation=%d credential_id=%s\n",
		result.ActiveSecurity.CredentialGeneration,
		result.ActiveSecurity.CredentialID)
	return nil
}

func main() {
	if err := run(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

Sample đã được format và compile-check với đúng Go connector. Nó không được chạy trong portal vì certificate, DNS và TLS-capable native profile là deployment inputs, không phải secret giả nên nhúng vào ví dụ.

06 · Failure law và trạng thái hiệu lực

Đọc failure ở boundary nơi nó xảy ra

Initial apply hoặc reload không hợp lệ
Synchronous apply result từ chối candidate và giữ nguyên immutable context đang active. Chưa có envelope nên không tạo deadletter.
Outbound handshake lỗi cho envelope đã được admit
CoAkka Runtime tạo REMOTE_TRANSPORT_SECURITY_FAILED với metadata có bound. Vì handshake xảy ra trước business bytes, delivery certainty là NOT_DELIVERED.
Inbound handshake lỗi trước khi decode request
Chưa có message_id hay envelope gốc. Core ghi ingress event REMOTE_TRANSPORT_FAILED, không tạo một deadletter giả.

Các nhóm chẩn đoán ổn định gồm invalid local config, handshake failure, untrusted/expired certificate, identity mismatch và client certificate bị thiếu. Connector và app branch theo reason/structured metadata, không parse câu chữ trong detail. Một failed hoặc stale reload không được làm thay đổi active generation.