aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/com/juick/service/ActivityPubService.java
blob: 75a3b488026e8ecca0bf86e8ded7324a5996b740 (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
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
/*
 * Copyright (C) 2008-2023, Juick
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package com.juick.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juick.model.AnonymousUser;
import com.juick.model.User;
import com.juick.util.DateFormattersHolder;
import com.juick.www.api.activity.model.Context;
import com.juick.www.api.activity.model.objects.Actor;
import jakarta.annotation.PostConstruct;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.core.convert.ConversionService;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.UriComponents;
import org.springframework.web.util.UriComponentsBuilder;
import org.tomitribe.auth.signatures.Base64;

import javax.annotation.Nonnull;
import javax.inject.Inject;
import java.io.IOException;
import java.net.URI;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.time.Instant;
import java.util.List;
import java.util.Optional;

@Repository
public class ActivityPubService extends BaseJdbcService implements SocialService {

    private static final Logger logger = LoggerFactory.getLogger("ActivityPub");

    @Value("${ap_base_uri:http://localhost:8080/}")
    private String baseUri;
    @Inject
    private UserService userService;
    @Inject
    private OkHttpClient httpClient;
    @Inject
    private ObjectMapper jsonMapper;
    @Inject
    private SignatureService signatureService;
    @Inject
    private User serviceUser;
    @Inject
    private ConversionService conversionService;

    private boolean isPublic;

    @PostConstruct
    public void init() {
        UriComponents baseUriComponents = UriComponentsBuilder.fromUriString(baseUri).build();
        isPublic = baseUriComponents.getScheme().equals("https");
        logger.info("Signed GET requests enabled: {}", isPublic);
    }
    @Transactional(readOnly = true)
    @Override
    public @Nonnull User getUserByAccountUri(String acct) {
        UriComponents baseUriComponents = UriComponentsBuilder.fromUriString(baseUri).build();
        UriComponents acctComponents = UriComponentsBuilder.fromUriString(acct).build();
        if (acctComponents.getHost().equals(baseUriComponents.getHost())) {
            // /u/ugnich -> ugnich
            String userName = acctComponents.getPath().substring(3);
            return userService.getUserByName(userName);
        }
        return AnonymousUser.INSTANCE;
    }

    @Transactional(readOnly = true)
    @Override
    public @Nonnull List<String> getFollowers(User user) {
        return getJdbcTemplate().queryForList("SELECT acct FROM followers WHERE user_id=?", String.class,
                user.getUid());
    }

    @Transactional
    @Override
    public void addFollower(User user, String acct) {
        try {
            getJdbcTemplate().update("INSERT INTO followers(user_id, acct) " +
                    "VALUES(?, ?)", user.getUid(), acct);
        } catch (DuplicateKeyException e) {
            // ignore
        }
    }

    @Transactional
    @Override
    public void removeFollower(User user, String acct) {
        getJdbcTemplate().update("DELETE FROM followers WHERE user_id=? AND acct=?", user.getUid(), acct);
    }

    @Transactional
    @Override
    public void removeAccount(String acct) {
        getJdbcTemplate().update("DELETE FROM followers WHERE acct=?", acct);
    }

    @Cacheable(value = "profiles", key="#contextUri")
    public Optional<Context> get(URI contextUri) {
        Instant now = Instant.now();
        String requestDate = DateFormattersHolder.getHttpDateFormatter().format(now);
        String host = contextUri.getPort() > 0 ? String.format("%s:%d", contextUri.getHost(), contextUri.getPort())
                : contextUri.getHost();
        var from = conversionService.convert(serviceUser, Actor.class);
        try {
            var request = new Request.Builder()
                    .url(contextUri.toURL())
                    .addHeader(HttpHeaders.ACCEPT, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE);
            if (isPublic) {
                String signatureString = signatureService.addSignature(from, host, "get", contextUri.getPath(), requestDate,
                        "");
                request.addHeader(HttpHeaders.DATE, requestDate)
                        .addHeader(HttpHeaders.HOST, host)
                        .addHeader("Signature", signatureString);
            }
            try (var response = httpClient.newCall(request.build()).execute()) {
                if (response.isSuccessful() && response.body() != null) {
                    var context = jsonMapper.readValue(response.body().string(), Context.class);
                    return Optional.of(context);
                }
            }
        } catch (Exception e) {
            logger.warn("HTTP Signature exception reading {}: {}", contextUri.toASCIIString(), e.getMessage());
        }
        return Optional.empty();
    }

    public int post(Actor from, Actor to, Context data) throws IOException, NoSuchAlgorithmException, InterruptedException {
        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();
        var finalContext = Context.build(data);
        var payload = jsonMapper.writeValueAsString(finalContext);
        final byte[] digest = MessageDigest.getInstance("SHA-256").digest(payload.getBytes()); // (1)
        final String digestHeader = "SHA-256=" + new String(Base64.encodeBase64(digest));
        String signatureString = signatureService.addSignature(from, host, "post", inbox.getPath(), requestDate,
                digestHeader);
        var body = RequestBody.create(payload, MediaType.get(Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE));
        var request = new Request.Builder()
                .url(inbox.toASCIIString())
                .post(body)
                .addHeader(HttpHeaders.DATE, requestDate)
                .addHeader(HttpHeaders.CONTENT_TYPE, Context.ACTIVITYSTREAMS_PROFILE_MEDIA_TYPE)
                .addHeader("Digest", digestHeader)
                .addHeader("Signature", signatureString)
                .build();
        logger.debug("Sending context to {}: {}", to.getId(), payload);
        try (var response = httpClient.newCall(request).execute()) {
            return response.code();
        }
    }
}