# Host tests for the hub credential module.
#
#   nix-shell -p gcc gnumake mbedtls --run 'cd tests/hub_creds && make && ./test_hub_creds'
#
# main/hub_creds.c is compiled straight from the firmware source, not copied,
# so the test cannot drift from what ships -- the same arrangement as
# main/script/test. What is replaced is the SDK underneath it: NVS becomes an
# in-memory map, FreeRTOS runs a task where it stands, and the MAC is fixed.
# mbedTLS is the real library, since the whole point is to exercise the
# certificate it actually writes.
#
# The host mbedTLS is whatever the shell provides (3.6.7 at the time of
# writing) against the firmware's 3.6.5. A patch version apart, and the APIs
# used here are unchanged between them; if that stops being true this is where
# it will fail to compile.

# _POSIX_C_SOURCE for strnlen, which hub_creds.c uses and which -std=c11
# alone hides. ESP-IDF compiles with GNU extensions on, so the firmware never
# noticed; a host test in strict C11 does.
CFLAGS += -O1 -g -std=c11 -D_POSIX_C_SOURCE=200809L -Wall -Wextra
SAN ?= -fsanitize=address,undefined -fno-omit-frame-pointer

MAIN = ../../main

INCLUDES = -Ishim -I$(MAIN)

# main.h is force-included so that its guard is already defined by the time
# hub_creds.c asks for it; see shim/main.h. datatypes.h and packet.h are the
# firmware's own -- they compile here unchanged, so there is no reason to
# shadow them and every reason not to: the packet id and the length limit are
# exactly the values that have to be right.
CFLAGS += -include shim/main.h

LIBS = -lmbedtls -lmbedx509 -lmbedcrypto

# crash_seal.c is here because hub_creds.c calls it: HUB_PROV_ADD_OWNER
# provisions a crash-report owner at the end of pairing. Linking the real
# module rather than stubbing it means an owner accepted over the hub is one
# that can actually seal -- which is where this went wrong once already, with
# a key read one byte off the dispatcher's pointer and rejected as "not a
# point on secp256r1".
SRCS = test_hub_creds.c shim/shim.c $(MAIN)/hub_creds.c $(MAIN)/buffer.c \
	$(MAIN)/crash_seal.c

all: test_hub_creds

test_hub_creds: $(SRCS) $(wildcard shim/*.h) $(MAIN)/hub_creds.h tool_certs.h
	$(CC) $(CFLAGS) $(SAN) $(INCLUDES) -o $@ $(SRCS) $(LIBS)

clean:
	rm -f test_hub_creds

.PHONY: all clean
