Skip to content

Commit de74e23

Browse files
committed
Added a public certificate service for downloading certificates by anyone
1 parent a9c17a2 commit de74e23

14 files changed

Lines changed: 400 additions & 9 deletions

File tree

‎AGENTS.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,9 @@ Sign-in is Google OAuth, pictures are stored in S3-compatible storage.
2424
- **Database schema:** Flyway migrations in `server-spring/src/main/resources/db/migration/`.
2525
- **API:** everything is under `/api`. Docs at <http://localhost:7777/api/docs> while the back-end
2626
runs.
27+
- **Certificates site:** the public pages where anyone can check a certificate are the back-end's
28+
`certificate/` feature under `/api/public/certificates`. The client's nginx serves them on the
29+
certificates domain.
2730
- **CI/CD:** `.github/workflows/`. `frontend-ci-cd.yml` and `server-ci-cd.yml` lint, test and build
2831
the Docker images, and push them to GHCR from `main`. `pr-security-review.lock.yml` is generated
2932
from `pr-security-review.md` by `gh aw compile`; never edit it by hand.

‎client/nginx.conf‎

Lines changed: 21 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -43,8 +43,27 @@ server {
4343
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
4444
}
4545

46-
# Proxy API docs requests to the backend.
47-
location /api-docs/ {
46+
# Fallback to index.html for client-side routing (React Router)
47+
location / {
48+
# Inject the Google client ID into index.html at runtime
49+
sub_filter '%VITE_GOOGLE_CLIENTID%' '${VITE_GOOGLE_CLIENTID}';
50+
try_files $uri $uri/ /index.html;
51+
}
52+
}
53+
54+
# The public certificates site on its own domain. The backend serves it under /api/public/certificates
55+
server {
56+
listen 80;
57+
server_name certificates.*;
58+
server_tokens off;
59+
# The pages load their styles, images and PDF from this host only
60+
add_header Content-Security-Policy "default-src 'none'; style-src 'self'; img-src 'self'; object-src 'self'; frame-src 'self'" always;
61+
62+
resolver ${NGINX_LOCAL_RESOLVERS} valid=10s;
63+
set $backend ${BACKEND_URL};
64+
65+
location / {
66+
rewrite ^ /api/public/certificates$uri break;
4867
proxy_pass $backend;
4968
proxy_ssl_server_name on;
5069
proxy_set_header Host $proxy_host;
@@ -53,11 +72,4 @@ server {
5372
proxy_set_header X-Real-IP $remote_addr;
5473
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
5574
}
56-
57-
# Fallback to index.html for client-side routing (React Router)
58-
location / {
59-
# Inject the Google client ID into index.html at runtime
60-
sub_filter '%VITE_GOOGLE_CLIENTID%' '${VITE_GOOGLE_CLIENTID}';
61-
try_files $uri $uri/ /index.html;
62-
}
6375
}

‎server-spring/AGENTS.md‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,12 @@ helpers and the `DojoException` family, and `shared/model/` the enums several fe
143143
so it fits inside whole. To delete an owner, delete and `flush()` it before
144144
`PictureService.deleteAll`. Locally, storage is the MinIO in `../server/dev-services`
145145
(`docker compose up storage`).
146+
- **Certificates** (`certificate/`): the public site where anyone can check a graduation
147+
certificate, the PDF at `certificates/<id>` in the bucket, so `/api/public/certificates/**` needs
148+
no sign-in. The client's nginx serves it on the certificates domain, where `/<path>` is
149+
`/api/public/certificates/<path>` here, and sets its Content-Security-Policy. It is a web site,
150+
so it answers with HTML pages, not `DojoError`, and is hidden from the API docs. The pages and
151+
their files are in `src/main/resources/certificates/`.
146152
- **Search** (`search/`): ranking runs in Java over every trainee, volunteer, organisation and
147153
contact person, because names match by close spelling. Each type ranks on its own, then a stable
148154
sort by score merges them, so equal scores list trainees first, then volunteers, organisations
Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
package nl.hackyourfuture.dojoserver.certificate;
2+
3+
import io.swagger.v3.oas.annotations.Hidden;
4+
import lombok.extern.slf4j.Slf4j;
5+
import nl.hackyourfuture.dojoserver.filestorage.FileStorageService;
6+
import nl.hackyourfuture.dojoserver.shared.exception.DojoNotFoundException;
7+
import org.springframework.core.io.ClassPathResource;
8+
import org.springframework.core.io.Resource;
9+
import org.springframework.http.HttpStatus;
10+
import org.springframework.http.MediaType;
11+
import org.springframework.http.MediaTypeFactory;
12+
import org.springframework.http.ResponseEntity;
13+
import org.springframework.web.bind.annotation.ExceptionHandler;
14+
import org.springframework.web.bind.annotation.GetMapping;
15+
import org.springframework.web.bind.annotation.PathVariable;
16+
import org.springframework.web.bind.annotation.RequestMapping;
17+
import org.springframework.web.bind.annotation.RestController;
18+
19+
import java.io.IOException;
20+
import java.io.InputStream;
21+
import java.nio.charset.StandardCharsets;
22+
23+
/** The public site where anyone can check a certificate. nginx serves it on its own domain, without the prefix. */
24+
@Hidden // A web site, not part of the API
25+
@RestController
26+
@RequestMapping("/api/public/certificates")
27+
@Slf4j
28+
public class CertificateController {
29+
// Letters, digits, - and _ only, so an id can't reach outside certificates/ in the bucket
30+
private static final String ID = "/{id:[a-zA-Z0-9_-]{1,10}}";
31+
32+
private final FileStorageService fileStorageService;
33+
private final String validPage;
34+
private final String notFoundPage;
35+
36+
public CertificateController(FileStorageService fileStorageService) throws IOException {
37+
this.fileStorageService = fileStorageService;
38+
this.validPage = new ClassPathResource("certificates/pages/index.html")
39+
.getContentAsString(StandardCharsets.UTF_8);
40+
this.notFoundPage =
41+
new ClassPathResource("certificates/pages/404.html").getContentAsString(StandardCharsets.UTF_8);
42+
}
43+
44+
@GetMapping(ID)
45+
public ResponseEntity<String> page(
46+
@PathVariable
47+
String id
48+
) {
49+
if (!fileStorageService.exists("certificates/" + id)) {
50+
log.info("Certificate {} not found", id);
51+
return notFound();
52+
}
53+
return html(HttpStatus.OK, validPage.replace("XXXXXXXX", id));
54+
}
55+
56+
@GetMapping(path = ID, params = "raw")
57+
public ResponseEntity<byte[]> pdf(@PathVariable
58+
String id) throws IOException {
59+
// Read it whole first, so a slow visitor never holds a bucket connection
60+
try (InputStream content = fileStorageService.download("certificates/" + id).content()) {
61+
return ResponseEntity.ok().contentType(MediaType.APPLICATION_PDF).body(content.readAllBytes());
62+
}
63+
}
64+
65+
// The stylesheets, logo, icon and robots.txt. The page templates are in pages/, so they are never sent as they are
66+
@GetMapping("/{file:[a-zA-Z0-9_-]+\\.[a-z]+}")
67+
public ResponseEntity<Resource> file(@PathVariable
68+
String file) {
69+
var resource = new ClassPathResource("certificates/static/" + file);
70+
if (!resource.exists()) {
71+
throw new DojoNotFoundException("File not found");
72+
}
73+
// Set from the file name, or content negotiation would pick JSON
74+
return ResponseEntity.ok()
75+
.contentType(MediaTypeFactory.getMediaType(resource).orElse(MediaType.APPLICATION_OCTET_STREAM))
76+
.body(resource);
77+
}
78+
79+
// Anything else, like / or /a/b
80+
@GetMapping("/**")
81+
public ResponseEntity<String> notFound() {
82+
return html(HttpStatus.NOT_FOUND, notFoundPage);
83+
}
84+
85+
// A missing PDF or file gets the not-found page too, not the API's JSON error
86+
@ExceptionHandler(DojoNotFoundException.class)
87+
public ResponseEntity<String> handleNotFound() {
88+
return notFound();
89+
}
90+
91+
private static ResponseEntity<String> html(HttpStatus status, String page) {
92+
return ResponseEntity.status(status).contentType(MediaType.TEXT_HTML).body(page);
93+
}
94+
}

‎server-spring/src/main/java/nl/hackyourfuture/dojoserver/config/security/SecurityConfig.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,8 +41,12 @@ public SecurityFilterChain securityFilterChain(
4141
.requestMatchers(HttpMethod.POST, "/api/auth/logout").permitAll()
4242
.requestMatchers("/actuator/health/**").permitAll()
4343
.requestMatchers("/api/docs/**").permitAll()
44+
// The certificates site, where anyone can check a certificate
45+
.requestMatchers("/api/public/certificates/**").permitAll()
4446
.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()
4547
.anyRequest().authenticated())
48+
// SAMEORIGIN like nginx, not Spring's DENY, so the certificate page can embed its PDF.
49+
.headers(headers -> headers.frameOptions(frame -> frame.sameOrigin()))
4650
// Filter-chain 401s and 403s never reach GlobalExceptionHandler; this gives them its shape.
4751
.exceptionHandling(exceptions -> exceptions
4852
.authenticationEntryPoint(securityErrorHandler)

‎server-spring/src/main/java/nl/hackyourfuture/dojoserver/filestorage/FileStorageService.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
import software.amazon.awssdk.services.s3.model.DeleteObjectRequest;
1515
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
1616
import software.amazon.awssdk.services.s3.model.GetObjectResponse;
17+
import software.amazon.awssdk.services.s3.model.HeadObjectRequest;
1718
import software.amazon.awssdk.services.s3.model.ListObjectsV2Request;
1819
import software.amazon.awssdk.services.s3.model.NoSuchKeyException;
1920
import software.amazon.awssdk.services.s3.model.PutObjectRequest;
@@ -84,6 +85,19 @@ public StoredFile download(String key) {
8485
return file;
8586
}
8687

88+
public boolean exists(String key) {
89+
var request = HeadObjectRequest.builder()
90+
.bucket(this.fileStorageProperties.bucket())
91+
.key(key)
92+
.build();
93+
try {
94+
this.s3Client.headObject(request);
95+
return true;
96+
} catch (NoSuchKeyException _) {
97+
return false;
98+
}
99+
}
100+
87101
public void delete(String key) {
88102
var request = DeleteObjectRequest.builder()
89103
.bucket(this.fileStorageProperties.bucket())
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>HackYourFuture Certificates</title>
7+
<link rel="stylesheet" href="/404.css" />
8+
</head>
9+
<body>
10+
<img id="hyf-logo" src="/HackYourFuture-logo.png" alt="HackYourFuture" />
11+
<p class="content">Sorry, we could not verify the certificate. Please make sure the URL is correct.</p>
12+
<p class="footer">
13+
If you have additional questions, please contact us at
14+
<a href="https://www.hackyourfuture.net/contact" target="_blank">https://www.hackyourfuture.net/contact</a>
15+
</p>
16+
</body>
17+
</html>
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<!doctype html>
2+
<html lang="en">
3+
<head>
4+
<meta charset="UTF-8" />
5+
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6+
<title>HackYourFuture Certificates</title>
7+
<link rel="stylesheet" href="/index.css" />
8+
</head>
9+
<body>
10+
<div class="header-section">
11+
<img id="hyf-logo" src="/HackYourFuture-logo.png" alt="HackYourFuture" />
12+
<h1 class="header">
13+
<img id="verified-icon" src="/verified-icon.svg" alt="Verified" />
14+
Certificate is valid
15+
</h1>
16+
</div>
17+
<div class="pdf-section">
18+
<div class="fancy-border">
19+
<object id="pdf-object" data="/XXXXXXXX?raw=1#toolbar=0" type="application/pdf">
20+
<embed src="/XXXXXXXX?raw=1" type="application/pdf" />
21+
</object>
22+
</div>
23+
</div>
24+
</body>
25+
</html>
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
body {
2+
padding: 50px;
3+
font-family: Arial, sans-serif;
4+
}
5+
#hyf-logo {
6+
width: 300px;
7+
}
8+
.content {
9+
font-size: 1.3rem;
10+
color: #333;
11+
}
12+
.footer {
13+
font-size: 1rem;
14+
color: #666;
15+
}
13.6 KB
Loading

0 commit comments

Comments
 (0)