: asapien/signet

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
79 
80 
81 
82 
83 
84 
85 
86 
87 
88 
89 
90 
91 
92 
93 
94 
95 
96 
97 
98 
99 
100 
101 
102 
103 
104 
105 
106 
107 
108 
109 
110 
111 
112 
113 
114 
115 
116 
117 
118 
119 
120 
121 
122 
123 
124 
125 
126 
127 
128 
129 
130 
131 
132 
133 
134 
135 
136 
137 
138 
139 
140 
141 
142 
143 
144 
145 
146 
147 
148 
149 
150 
151 
152 
153 
154 
155 
156 
157 
158 
159 
160 
161 
162 
163 
164 
165 
166 
167 
168 
169 
170 
171 
172 
173 
174 
175 
176 
177 
178 
179 
180 
181 
182 
183 
184 
185 
186 
187 
188 
189 
190 
191 
192 
193 
194 
195 
196 
197 
198 
199 
200 
201 
202 
203 
204 
205 
206 
207 
208 
209 
210 
211 
212 
213 
214 
215 
216 
217 
218 
219 
220 
221 
222 
223 
224 
225 
226 
227 
228 
229 
230 
231 
232 
233 
234 
235 
236 
237 
238 
239 
240 
241 
242 
243 
244 
245 
246 
247 
248 
249 
250 
251 
252 
253 
254 
255 
256 
257 
258 
259 
260 
261 
262 
263 
264 
265 
266 
267 
268 
269 
270 
271 
272 
273 
274 
275 
276 
277 
278 
279 
280 
281 
282 
283 
284 
285 
286 
287 
288 
289 
290 
291 
292 
293 
294 
295 
296 
297 
298 
299 
300 
301 
302 
303 
304 
305 
306 
307 
308 
309 
310 
311 
312 
313 
314 
315 
316 
317 
318 
319 
320 
321 
322 
323 
324 
325 
#include <sys/stat.h>

#include <dirent.h>
#include <errno.h>
#include <fcntl.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

#include "snapshot.h"
#include "util.h"

#define MAX_ASSETS 201 /* 200 imprints plus the audit font. */
#define MAX_ASSET_BYTES (16u * 1024 * 1024) /* Aggregate frozen inputs, streamed. */

struct asset {
	char ref[1024], name[32];
};

/* Open every DAM component without following symlinks, including directories. */
static int
open_asset(const char *dam, const char *ref)
{
	char path[1024], *part, *next;
	int dir, fd;

	if (!is_safe_relpath(ref) || strlen(ref) >= sizeof(path))
		return -1;
	strcpy(path, ref);
	if ((dir = open(dam, O_RDONLY | O_DIRECTORY)) == -1)
		return -1;
	for (part = path; (next = strchr(part, '/')) != NULL; part = next + 1) {
		*next = '\0';
		fd = openat(dir, part, O_RDONLY | O_DIRECTORY | O_NOFOLLOW);
		close(dir);
		if (fd == -1)
			return -1;
		dir = fd;
	}
	fd = openat(dir, part, O_RDONLY | O_NOFOLLOW | O_NONBLOCK);
	close(dir);
	return fd;
}

static int
freeze_asset(const struct conf *cf, const char *ref, const char *dir,
    struct asset assets[MAX_ASSETS], int *count, size_t *total, yyjson_mut_doc *doc,
    yyjson_mut_val *files, char name[32])
{
	char dest[1200], buf[16384], hash[65];
	struct stat before, after;
	yyjson_mut_val *file;
	ssize_t n, written;
	int i, in, out = -1, rv = -1;
	size_t copied = 0;

	for (i = 0; i < *count; i++)
		if (strcmp(assets[i].ref, ref) == 0) {
			strcpy(name, assets[i].name);
			return 0;
		}
	if (*count == MAX_ASSETS || strlen(ref) >= sizeof(assets[0].ref))
		return -1;
	in = open_asset(conf_get(cf, "dam_dir", "/var/www/dam"), ref);
	if (in == -1)
		return -1;
	if (fstat(in, &before) == -1 || !S_ISREG(before.st_mode) ||
	    before.st_size < 1 || (uint64_t)before.st_size > MAX_ASSET_BYTES - *total)
		goto out;
	snprintf(name, 32, "asset-%d", *count);
	snprintf(dest, sizeof(dest), "%s/%s", dir, name);
	if ((out = open(dest, O_WRONLY | O_CREAT | O_EXCL, 0640)) == -1)
		goto out;
	while ((n = read(in, buf, sizeof(buf))) != 0) {
		if (n == -1) {
			if (errno == EINTR)
				continue;
			goto out;
		}
		if ((size_t)n > (size_t)before.st_size - copied)
			goto out;
		copied += (size_t)n;
		for (written = 0; written < n;) {
			ssize_t step = write(out, buf + written, (size_t)(n - written));
			if (step == -1 && errno == EINTR)
				continue;
			if (step <= 0)
				goto out;
			written += step;
		}
	}
	/* Reject in-place edits during the copy; atomic replacement keeps this fd stable. */
	if (fstat(in, &after) == -1 || copied != (size_t)before.st_size || before.st_size != after.st_size ||
	    before.st_mtim.tv_sec != after.st_mtim.tv_sec ||
	    before.st_mtim.tv_nsec != after.st_mtim.tv_nsec ||
	    before.st_ctim.tv_sec != after.st_ctim.tv_sec ||
	    before.st_ctim.tv_nsec != after.st_ctim.tv_nsec ||
	    fchmod(out, 0440) == -1 || fsync(out) == -1)
		goto out;
	if (close(out) == -1) {
		out = -1;
		goto out;
	}
	out = -1;
	if (sha256_file(dest, hash) == -1)
		goto out;
	file = yyjson_mut_obj(doc);
	if (file == NULL || !yyjson_mut_obj_add_strcpy(doc, file, "name", name) ||
	    !yyjson_mut_obj_add_strcpy(doc, file, "sha256", hash) ||
	    !yyjson_mut_arr_append(files, file))
		goto out;
	strcpy(assets[*count].ref, ref);
	strcpy(assets[*count].name, name);
	(*count)++;
	*total += copied;
	rv = 0;
out:
	if (out != -1)
		close(out);
	close(in);
	return rv;
}

/* One bounded, atomic Redis read of just the referenced organisation attributes. */
static redisReply *
read_attributes(redisContext *rc, const char *org, yyjson_val *layout)
{
	static const char script[] =
	    "local t,i={},{}; for n=1,#ARGV,2 do "
	    "local a,k; if ARGV[n]=='t' then a=t; k=KEYS[1] else a=i; k=KEYS[2] end; "
	    "local v=redis.call('HGET',k,ARGV[n+1]); "
	    "if not v or #v>1023 or string.find(v,string.char(0),1,true) then "
	    "return redis.error_reply('missing or invalid snapshot attribute') end; "
	    "a[#a+1]=ARGV[n+1]; a[#a+1]=v; end; return {t,i}";
	const char *argv[405] = { "EVAL", script, "2" };
	char metadata[128], images[128];
	yyjson_val *imp;
	const char *type;
	size_t i, max;
	int argc = 5;

	if (rc == NULL)
		return NULL;
	snprintf(metadata, sizeof(metadata), "%s:metadata", org);
	snprintf(images, sizeof(images), "%s:images", org);
	argv[3] = metadata;
	argv[4] = images;
	yyjson_arr_foreach(yyjson_obj_get(layout, "imprints"), i, max, imp) {
		type = yyjson_get_str(yyjson_obj_get(imp, "type"));
		if (strcmp(type, "pim_text") != 0 && strcmp(type, "pim_image") != 0)
			continue;
		if (argc + 2 > (int)(sizeof(argv) / sizeof(argv[0])))
			return NULL;
		argv[argc++] = strcmp(type, "pim_text") == 0 ? "t" : "i";
		argv[argc++] = yyjson_get_str(yyjson_obj_get(imp, "ref"));
	}
	return argc == 5 ? NULL : redisCommandArgv(rc, argc, argv, NULL);
}

static const char *
attribute(redisReply *hash, const char *ref)
{
	size_t i;

	if (hash == NULL || hash->type != REDIS_REPLY_ARRAY || ref == NULL)
		return NULL;
	for (i = 0; i + 1 < hash->elements; i += 2)
		if (hash->element[i]->type == REDIS_REPLY_STRING &&
		    hash->element[i + 1]->type == REDIS_REPLY_STRING &&
		    strcmp(hash->element[i]->str, ref) == 0)
			return hash->element[i + 1]->str;
	return NULL;
}

char *
snapshot_create(const struct conf *cf, redisContext *rc, const char *org,
    int revision, yyjson_val *layout, const char *dir, char *err, size_t errsz)
{
	struct asset assets[MAX_ASSETS];
	yyjson_mut_doc *doc = yyjson_mut_doc_new(NULL);
	yyjson_mut_val *root, *frozen, *imps, *imp, *files;
	redisReply *pim = NULL, *text = NULL, *images = NULL;
	const char *type, *ref, *value, *font, *prefix;
	char name[32], manifest[1200], *result = NULL;
	size_t i, max, total = 0;
	int count = 0, created = 0, fd, parent, complete = 0;

	if (doc == NULL)
		goto out;
	root = yyjson_mut_obj(doc);
	frozen = yyjson_val_mut_copy(doc, layout);
	files = yyjson_mut_arr(doc);
	if (root == NULL || frozen == NULL || files == NULL || mkdir(dir, 0750) == -1)
		goto out;
	created = 1;
	yyjson_mut_doc_set_root(doc, root);
	if (!yyjson_mut_obj_add_int(doc, root, "version", 1) ||
	    !yyjson_mut_obj_add_int(doc, root, "revision", revision) ||
	    !yyjson_mut_obj_add_strcpy(doc, root, "org_code", org) ||
	    !yyjson_mut_obj_add_val(doc, root, "layout", frozen) ||
	    !yyjson_mut_obj_add_val(doc, root, "files", files) ||
	    !yyjson_mut_obj_add_strcpy(doc, root, "date_format", conf_get(cf, "date_format", "%d-%m-%Y")))
		goto out;
	font = conf_get(cf, "default_font", "");
	name[0] = '\0';
	if (*font && freeze_asset(cf, font, dir, assets, &count, &total, doc, files, name) == -1)
		goto out;
	if (!yyjson_mut_obj_add_strcpy(doc, root, "default_font", name))
		goto out;
	pim = read_attributes(rc, org, layout);
	if (pim != NULL && pim->type == REDIS_REPLY_ARRAY && pim->elements == 2) {
		text = pim->element[0];
		images = pim->element[1];
	}
	imps = yyjson_mut_obj_get(frozen, "imprints");
	yyjson_mut_arr_foreach(imps, i, max, imp) {
		type = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "type"));
		ref = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "ref"));
		if (strcmp(type, "pim_text") == 0) {
			value = attribute(text, ref);
			prefix = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "prefix"));
			if (value == NULL || strlen(value) + (prefix ? strlen(prefix) : 0) > 1023 || !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "type"), yyjson_mut_str(doc, "resolved_text")) ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "value"), yyjson_mut_strcpy(doc, value)))
				goto out;
		} else if (strcmp(type, "pim_image") == 0) {
			value = attribute(images, ref);
			if (value == NULL || freeze_asset(cf, value, dir, assets, &count, &total, doc, files, name) == -1 ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "type"), yyjson_mut_str(doc, "frozen_image")) ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "ref"), yyjson_mut_strcpy(doc, name)))
				goto out;
		}
		if (strcmp(type, "pim_text") == 0 || strcmp(type, "date") == 0 || strcmp(type, "serial") == 0) {
			font = yyjson_mut_get_str(yyjson_mut_obj_get(imp, "font"));
			if (font == NULL || !*font)
				font = conf_get(cf, "default_font", "");
			name[0] = '\0';
			if ((*font && freeze_asset(cf, font, dir, assets, &count, &total, doc, files, name) == -1) ||
			    !yyjson_mut_obj_put(imp, yyjson_mut_str(doc, "font"), yyjson_mut_strcpy(doc, name)))
				goto out;
		}
	}
	/* Keep every revision's resolved metadata, even after the DB points at a correction. */
	result = yyjson_mut_write(doc, 0, NULL);
	snprintf(manifest, sizeof(manifest), "%s/manifest.json", dir);
	if (result == NULL || write_file(manifest, result, strlen(result), 0440) == -1 ||
	    (fd = open(manifest, O_RDONLY)) == -1)
		goto out;
	if (fchmod(fd, 0440) == -1 || fsync(fd) == -1) {
		close(fd);
		goto out;
	}
	close(fd);
	if (chmod(dir, 0550) == -1 || (fd = open(dir, O_RDONLY | O_DIRECTORY)) == -1)
		goto out;
	if (fsync(fd) == -1) {
		close(fd);
		goto out;
	}
	parent = openat(fd, "..", O_RDONLY | O_DIRECTORY);
	close(fd);
	if (parent == -1)
		goto out;
	if (fsync(parent) == -1) {
		close(parent);
		goto out;
	}
	close(parent);
	complete = 1;
out:
	if (!complete) {
		free(result);
		result = NULL;
		if (created)
			snapshot_remove(dir);
		snprintf(err, errsz, "could not freeze submit inputs (missing, unsafe, changing, text over 1023 bytes or assets over 16 MB)");
	}
	if (pim != NULL)
		freeReplyObject(pim);
	yyjson_mut_doc_free(doc);
	return result;
}

void
snapshot_remove(const char *dir)
{
	DIR *d;
	struct dirent *entry;

	if (dir == NULL || !*dir || chmod(dir, 0750) == -1 || (d = opendir(dir)) == NULL)
		return;
	while ((entry = readdir(d)) != NULL)
		if ((strncmp(entry->d_name, "asset-", 6) == 0 && is_safe_name(entry->d_name)) ||
		    strcmp(entry->d_name, "manifest.json") == 0)
			unlinkat(dirfd(d), entry->d_name, 0);
	closedir(d);
	rmdir(dir);
}

int
snapshot_verify(yyjson_val *root, const char *dir, char *err, size_t errsz)
{
	yyjson_val *files = yyjson_obj_get(root, "files"), *file;
	const char *name, *expected;
	char path[1200], hash[65];
	size_t i, max;

	if (yyjson_get_sint(yyjson_obj_get(root, "version")) != 1 || !yyjson_is_arr(files) ||
	    yyjson_arr_size(files) > MAX_ASSETS)
		goto fail;
	yyjson_arr_foreach(files, i, max, file) {
		name = yyjson_get_str(yyjson_obj_get(file, "name"));
		expected = yyjson_get_str(yyjson_obj_get(file, "sha256"));
		if (!is_safe_name(name) || expected == NULL)
			goto fail;
		snprintf(path, sizeof(path), "%s/%s", dir, name);
		if (sha256_file(path, hash) == -1 || strcmp(hash, expected) != 0)
			goto fail;
	}
	return 0;
fail:
	snprintf(err, errsz, "frozen revision inputs missing or damaged; live PIM/DAM fallback is forbidden");
	return -1;
}