aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/server/SignatureManager.java
blob: c863ae0ff8f83444dc10a2d98d97658298ba5e51 (plain) (blame)
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
package com.juick.server;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juick.User;
import com.juick.model.AnonymousUser;
import com.juick.server.api.activity.model.Context;
import com.juick.server.api.activity.model.objects.Person;
import com.juick.server.api.webfinger.model.Account;
import com.juick.server.api.webfinger.model.Link;
import com.juick.service.UserService;
import com.juick.util.DateFormattersHolder;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;
import org.tomitribe.auth.signatures.Signature;
import org.tomitribe.auth.signatures.Signer;
import org.tomitribe.auth.signatures.Verifier;
import rocks.xmpp.addr.Jid;

import javax.inject.Inject;
import java.io.IOException;
import java.net.URI;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.SignatureException;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

import static com.juick.server.api.activity.model.Context.ACTIVITY_MEDIA_TYPE;

@Component
public class SignatureManager {
    private static final Logger logger = LoggerFactory.getLogger(ActivityPubManager.class);
    @Inject
    private KeystoreManager keystoreManager;
    @Inject
    private ObjectMapper jsonMapper;
    @Inject
    private UserService userService;
    @Inject
    private RestTemplate apClient;

    public void post(Person from, Person to, Context data) throws IOException {
        UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(to.getInbox());
        URI inbox = uriComponentsBuilder.build().toUri();
        Instant now = Instant.now();
        String requestDate = DateFormattersHolder.getHttpDateFormatter().format(now);
        String host = inbox.getPort() > 0 ? String.format("%s:%d", inbox.getHost(), inbox.getPort()) : inbox.getHost();
        String signatureString = addSignature(from, host, "POST", inbox.getPath(), requestDate);

        HttpHeaders requestHeaders = new HttpHeaders();
        requestHeaders.add("Content-Type", Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE);
        requestHeaders.add("Date", requestDate);
        requestHeaders.add("Host", host);
        requestHeaders.add("Signature", signatureString);
        HttpEntity<Context> request = new HttpEntity<>(Context.build(data), requestHeaders);
        logger.info("Sending context: {}", jsonMapper.writeValueAsString(data));
        logger.info("Request date: {}", requestDate);
        ResponseEntity<Void> response = apClient.postForEntity(inbox, request, Void.class);
        logger.info("accepted follower: {}", response.getStatusCodeValue());
    }

    public String addSignature(Person from, String host, String method, String path, String dateString) throws IOException {
        return addSignature(from, host, method, path, dateString, keystoreManager);
    }

    public String addSignature(Person from, String host, String method, String path, String dateString, KeystoreManager keystoreManager) throws IOException {
        Signature templateSignature = new Signature(from.getPublicKey().getId(), "rsa-sha256", null,
                "(request-target)", "host", "date");
        Map<String, String> headers = new HashMap<>();
        headers.put("host", host);
        headers.put("date", dateString);
        Signer signer = new Signer(keystoreManager.getPrivateKey(), templateSignature);
        Signature signature = signer.sign(method, path, headers);
        // remove "Signature: " from result
        return signature.toString().substring(10);
    }

    public User verifySignature(String method, String path, Map<String, String> headers) {
        String signatureString = headers.get("signature");
        logger.info("Signature: {}", signatureString);
        Signature signature = Signature.fromString(signatureString);
        Optional<Context> context = getContext(UriComponentsBuilder.fromUriString(signature.getKeyId())
                .fragment(null).build().toUri());
        if (context.isPresent() && context.get() instanceof Person) {
            Person person = (Person) context.get();
            Key key = KeystoreManager.publicKeyOf(person);

            Verifier verifier = new Verifier(key, signature);
            try {
                boolean result = verifier.verify(method, path, headers);
                logger.info("signature of {} is valid: {}", signature.getKeyId(), result);
                if (result) {
                    User user = new User();
                    user.setUri(URI.create(person.getId()));
                    if (key.equals(keystoreManager.getPublicKey())) {
                        return userService.getUserByName(person.getName());
                    }
                    return user;
                } else {
                    return AnonymousUser.INSTANCE;
                }
            } catch (NoSuchAlgorithmException | SignatureException | IOException e) {
                logger.warn("Invalid signature {}", signatureString);
            }
        } else {
            logger.warn("Unknown keyId");
        }
        return AnonymousUser.INSTANCE;
    }
    public Optional<Context> getContext(URI contextUri) {
        try {
            Context context = apClient.getForEntity(contextUri, Context.class).getBody();
            if (context == null) {
                logger.warn("Cannot identify {}", contextUri);
                return Optional.empty();
            }
            return Optional.of(context);
        } catch (Exception e) {
            logger.warn("REST Exception processing {}", contextUri, e);
        }
        return Optional.empty();
    }
    public Optional<Context> discoverPerson(String acct) {
        String[] accountParts = acct.split(":", 2);
        String account = accountParts[0];
        int port = accountParts.length > 1 ? Integer.valueOf(accountParts[1]) : 80;
        Jid acctId = Jid.of(account);
        URI resourceUri = UriComponentsBuilder.fromUriString(
                String.format("http://%s:%d/.well-known/webfinger?resource=acct:%s", acctId.getDomain(), port, account)).build().toUri();
        Account acctData = apClient.getForEntity(resourceUri, Account.class).getBody();
        if (acctData != null) {
            for (Link l : acctData.getLinks()) {
                if (l.getRel().equals("self") && l.getType().equals(ACTIVITY_MEDIA_TYPE)) {
                    return getContext(URI.create(l.getHref()));
                }
            }
        }
        return Optional.empty();
    }
}