summaryrefslogtreecommitdiffstats
path: root/extensions/PhabBugz/lib/Util.pm
blob: cd396602e0bd7aa55facc5758b84b0577e7a2ade (plain)
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
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
# This Source Code Form is subject to the terms of the Mozilla Public
# License, v. 2.0. If a copy of the MPL was not distributed with this
# file, You can obtain one at http://mozilla.org/MPL/2.0/.
#
# This Source Code Form is "Incompatible With Secondary Licenses", as
# defined by the Mozilla Public License, v. 2.0.

package Bugzilla::Extension::PhabBugz::Util;

use 5.10.1;
use strict;
use warnings;

use Bugzilla::Bug;
use Bugzilla::Constants;
use Bugzilla::Error;
use Bugzilla::User;
use Bugzilla::Util qw(trim);
use Bugzilla::Extension::PhabBugz::Constants;

use JSON::XS qw(encode_json decode_json);
use List::Util qw(first);
use LWP::UserAgent;

use base qw(Exporter);

our @EXPORT = qw(
    add_comment_to_revision
    add_security_sync_comments
    create_revision_attachment
    create_private_revision_policy
    create_project
    edit_revision_policy
    get_attachment_revisions
    get_bug_role_phids
    get_members_by_bmo_id
    get_members_by_phid
    get_phab_bmo_ids
    get_project_phid
    get_revisions_by_ids
    get_revisions_by_phids
    get_security_sync_groups
    intersect
    is_attachment_phab_revision
    make_revision_private
    make_revision_public
    request
    set_phab_user
    set_project_members
    set_revision_subscribers
);

sub get_revisions_by_ids {
    my ($ids) = @_;
    return _get_revisions({ ids => $ids });
}

sub get_revisions_by_phids {
    my ($phids) = @_;
    return _get_revisions({ phids => $phids });
}

sub _get_revisions {
    my ($constraints) = @_;

    my $data = {
        queryKey    => 'all',
        constraints => $constraints
    };

    my $result = request('differential.revision.search', $data);

    ThrowUserError('invalid_phabricator_revision_id')
        unless (exists $result->{result}{data} && @{ $result->{result}{data} });

    return $result->{result}{data};
}

sub create_revision_attachment {
    my ( $bug, $revision, $timestamp ) = @_;

    my $phab_base_uri = Bugzilla->params->{phabricator_base_uri};
    ThrowUserError('invalid_phabricator_uri') unless $phab_base_uri;

    my $revision_uri = $phab_base_uri . "D" . $revision->id;

    # Check for previous attachment with same revision id.
    # If one matches then return it instead. This is fine as
    # BMO does not contain actual diff content.
    my @review_attachments = grep { is_attachment_phab_revision($_) } @{ $bug->attachments };
    my $review_attachment = first { trim($_->data) eq $revision_uri } @review_attachments;
    return $review_attachment if defined $review_attachment;

    # No attachment is present, so we can now create new one

    if (!$timestamp) {
        ($timestamp) = Bugzilla->dbh->selectrow_array("SELECT NOW()");
    }

    my $attachment = Bugzilla::Attachment->create(
        {
            bug         => $bug,
            creation_ts => $timestamp,
            data        => $revision_uri,
            description => $revision->title,
            filename    => 'phabricator-D' . $revision->id . '-url.txt',
            ispatch     => 0,
            isprivate   => 0,
            mimetype    => PHAB_CONTENT_TYPE,
        }
    );

    # Insert a comment about the new attachment into the database.
    $bug->add_comment($revision->summary, { type       => CMT_ATTACHMENT_CREATED,
                                            extra_data => $attachment->id });

    return $attachment;
}

sub intersect {
    my ($list1, $list2) = @_;
    my %e = map { $_ => undef } @{$list1};
    return grep { exists( $e{$_} ) } @{$list2};
}

sub get_bug_role_phids {
    my ($bug) = @_;

    my @bug_users = ( $bug->reporter );
    push(@bug_users, $bug->assigned_to)
        if $bug->assigned_to->email !~ /^nobody\@mozilla\.org$/;
    push(@bug_users, $bug->qa_contact) if $bug->qa_contact;
    push(@bug_users, @{ $bug->cc_users }) if @{ $bug->cc_users };

    return get_members_by_bmo_id(\@bug_users);
}

sub create_private_revision_policy {
    my ($bug, $groups) = @_;

    my $data = {
        objectType => 'DREV',
        default    => 'deny',
        policy     => [
            {
                action => 'allow',
                rule   => 'PhabricatorSubscriptionsSubscribersPolicyRule',
            }
        ]
    };

    if(scalar @$groups gt 0) {
        my $project_phids = [];
        foreach my $group (@$groups) {
            my $phid = get_project_phid('bmo-' . $group);
            push(@$project_phids, $phid) if $phid;
        }

        ThrowUserError('invalid_phabricator_sync_groups') unless @$project_phids;

        push(@{ $data->{policy} },
            {
                action => 'allow',
                rule   => 'PhabricatorProjectsPolicyRule',
                value  => $project_phids,
            }
        );
    }
    else {
        my $secure_revision = Bugzilla::Extension::PhabBugz::Project->new_from_query({
            name => 'secure-revision'
        });
        push(@{ $data->{policy} },
            {
                action => 'allow',
                value  => $secure_revision->phid,
            }
        );
    }

    my $result = request('policy.create', $data);
    return $result->{result}{phid};
}

sub make_revision_public {
    my ($revision_phid) = @_;
    return request('differential.revision.edit', {
        transactions => [
            {
                type  => 'view',
                value => 'public'
            },
            {
                type  => 'edit',
                value => 'users'
            }
        ],
        objectIdentifier => $revision_phid
    });
}

sub make_revision_private {
    my ($revision_phid) = @_;

    my $secure_revision = Bugzilla::Extension::PhabBugz::Project->new_from_query({
        name => 'secure-revision'
    });

    return request('differential.revision.edit', {
        transactions => [
            {
                type  => "view",
                value => $secure_revision->phid
            },
            {
                type  => "edit",
                value => $secure_revision->phid
            }
        ],
        objectIdentifier => $revision_phid
    });
}

sub edit_revision_policy {
    my ($revision_phid, $policy_phid, $subscribers) = @_;

    my $data = {
        transactions => [
            {
                type  => 'view',
                value => $policy_phid
            },
            {
                type  => 'edit',
                value => $policy_phid
            }
        ],
        objectIdentifier => $revision_phid
    };

    if (@$subscribers) {
        push(@{ $data->{transactions} }, {
            type  => 'subscribers.set',
            value => $subscribers
        });
    }

    return request('differential.revision.edit', $data);
}

sub set_revision_subscribers {
    my ($revision_phid, $subscribers) = @_;

    my $data = {
        transactions => [
            {
                type  => 'subscribers.set',
                value => $subscribers
            }
        ],
        objectIdentifier => $revision_phid
    };

    return request('differential.revision.edit', $data);
}

sub add_comment_to_revision {
    my ($revision_phid, $comment) = @_;

    my $data = {
        transactions => [
            {
                type  => 'comment',
                value => $comment
            }
        ],
        objectIdentifier => $revision_phid
    };
    return request('differential.revision.edit', $data);
}

sub get_project_phid {
    my $project = shift;
    my $memcache = Bugzilla->memcached;

    # Check memcache
    my $project_phid = $memcache->get_config({ key => "phab_project_phid_" . $project });
    if (!$project_phid) {
        my $data = {
            queryKey => 'all',
            constraints => {
                name => $project
            }
        };

        my $result = request('project.search', $data);
        return undef
            unless (exists $result->{result}{data} && @{ $result->{result}{data} });

        # If name is used as a query param, we need to loop through and look
        # for exact match as Conduit will tokenize the name instead of doing
        # exact string match :(
        foreach my $item ( @{ $result->{result}{data} } ) {
            next if $item->{fields}{name} ne $project;
            $project_phid = $item->{phid};
        }

        $memcache->set_config({ key => "phab_project_phid_" . $project, data => $project_phid });
    }
    return $project_phid;
}

sub create_project {
    my ($project, $description, $members) = @_;

    my $secure_revision = Bugzilla::Extension::PhabBugz::Project->new_from_query({
        name => 'secure-revision'
    });

    my $data = {
        transactions => [
            { type => 'name',  value => $project               },
            { type => 'description', value => $description     },
            { type => 'edit',  value => $secure_revision->phid }.
            { type => 'join',  value => $secure_revision->phid },
            { type => 'view',  value => $secure_revision->phid },
            { type => 'icon',  value => 'group'                },
            { type => 'color', value => 'red'                  }
        ]
    };

    my $result = request('project.edit', $data);
    return $result->{result}{object}{phid};
}

sub set_project_members {
    my ($project_id, $phab_user_ids) = @_;

    my $data = {
        objectIdentifier => $project_id,
        transactions => [
            { type => 'members.set',  value => $phab_user_ids }
        ]
    };

    my $result = request('project.edit', $data);
    return $result->{result}{object}{phid};
}

sub get_members_by_bmo_id {
    my $users = shift;

    my $result = get_phab_bmo_ids({ ids => [ map { $_->id } @$users ] });

    my @phab_ids;
    foreach my $user (@$result) {
        push(@phab_ids, $user->{phid})
          if ($user->{phid} && $user->{phid} =~ /^PHID-USER/);
    }

    return \@phab_ids;
}

sub get_members_by_phid {
    my $phids = shift;

    my $result = get_phab_bmo_ids({ phids => $phids });

    my @bmo_ids;
    foreach my $user (@$result) {
        push(@bmo_ids, $user->{id})
          if ($user->{phid} && $user->{phid} =~ /^PHID-USER/);
    }

    return \@bmo_ids;
}

sub get_phab_bmo_ids {
    my ($params) = @_;
    my $memcache = Bugzilla->memcached;

    # Try to find the values in memcache first
    my @results;
    if ($params->{ids}) {
        my @bmo_ids = @{ $params->{ids} };
        for (my $i = 0; $i < @bmo_ids; $i++) {
            my $phid = $memcache->get({ key => "phab_user_bmo_id_" . $bmo_ids[$i] });
            if ($phid) {
                push(@results, {
                    id   => $bmo_ids[$i],
                    phid => $phid
                });
                splice(@bmo_ids, $i, 1);
            }
        }
        $params->{ids} = \@bmo_ids;
    }

    if ($params->{phids}) {
        my @phids = @{ $params->{phids} };
        for (my $i = 0; $i < @phids; $i++) {
            my $bmo_id = $memcache->get({ key => "phab_user_phid_" . $phids[$i] });
            if ($bmo_id) {
                push(@results, {
                    id   => $bmo_id,
                    phid => $phids[$i]
                });
                splice(@phids, $i, 1);
            }
        }
        $params->{phids} = \@phids;
    }

    my $result = request('bugzilla.account.search', $params);

    # Store new values in memcache for later retrieval
    foreach my $user (@{ $result->{result} }) {
        $memcache->set({ key   => "phab_user_bmo_id_" . $user->{id},
                         value => $user->{phid} });
        $memcache->set({ key   => "phab_user_phid_" . $user->{phid},
                         value => $user->{id} });
        push(@results, $user);
    }

    return \@results;
}

sub is_attachment_phab_revision {
    my ($attachment) = @_;
    return ($attachment->contenttype eq PHAB_CONTENT_TYPE
            && $attachment->attacher->login eq PHAB_AUTOMATION_USER) ? 1 : 0;
}

sub get_attachment_revisions {
    my $bug = shift;

    my $revisions;

    my @attachments =
      grep { is_attachment_phab_revision($_) } @{ $bug->attachments() };

    if (@attachments) {
        my @revision_ids;
        foreach my $attachment (@attachments) {
            my ($revision_id) =
              ( $attachment->filename =~ PHAB_ATTACHMENT_PATTERN );
            next if !$revision_id;
            push( @revision_ids, int($revision_id) );
        }

        if (@revision_ids) {
            $revisions = get_revisions_by_ids( \@revision_ids );
        }
    }

    return @$revisions;
}

sub request {
    my ($method, $data) = @_;
    my $request_cache = Bugzilla->request_cache;
    my $params        = Bugzilla->params;

    my $ua = $request_cache->{phabricator_ua};
    unless ($ua) {
        $ua = $request_cache->{phabricator_ua} = LWP::UserAgent->new(timeout => 10);
        if ($params->{proxy_url}) {
            $ua->proxy('https', $params->{proxy_url});
        }
        $ua->default_header('Content-Type' => 'application/x-www-form-urlencoded');
    }

    my $phab_api_key = $params->{phabricator_api_key};
    ThrowUserError('invalid_phabricator_api_key') unless $phab_api_key;
    my $phab_base_uri = $params->{phabricator_base_uri};
    ThrowUserError('invalid_phabricator_uri') unless $phab_base_uri;

    my $full_uri = $phab_base_uri . '/api/' . $method;

    $data->{__conduit__} = { token => $phab_api_key };

    my $response = $ua->post($full_uri, { params => encode_json($data) });

    ThrowCodeError('phabricator_api_error', { reason => $response->message })
      if $response->is_error;

    my $result;
    my $result_ok = eval { $result = decode_json( $response->content); 1 };
    if (!$result_ok || $result->{error_code}) {
        ThrowCodeError('phabricator_api_error',
            { reason => 'JSON decode failure' }) if !$result_ok;
        ThrowCodeError('phabricator_api_error',
            { code   => $result->{error_code},
              reason => $result->{error_info} }) if $result->{error_code};
    }

    return $result;
}

sub get_security_sync_groups {
    my $bug = shift;

    my $phab_sync_groups = Bugzilla->params->{phabricator_sync_groups}
        || ThrowUserError('invalid_phabricator_sync_groups');
    my $sync_group_names = [ split('[,\s]+', $phab_sync_groups) ];

    my $bug_groups = $bug->groups_in;
    my $bug_group_names = [ map { $_->name } @$bug_groups ];

    my @set_groups = intersect($bug_group_names, $sync_group_names);

    return @set_groups;
}

sub set_phab_user {
    my $old_user = Bugzilla->user;
    my $user = Bugzilla::User->new( { name => PHAB_AUTOMATION_USER } );
    $user->{groups} = [ Bugzilla::Group->get_all ];
    Bugzilla->set_user($user);
    return $old_user;
}

sub add_security_sync_comments {
    my ($revisions, $bug) = @_;

    my $phab_error_message = 'Revision is being made private due to unknown Bugzilla groups.';

    foreach my $revision (@$revisions) {
        add_comment_to_revision( $revision->{phid}, $phab_error_message );
    }

    my $num_revisions = scalar @$revisions;
    my $bmo_error_message =
    ( $num_revisions > 1
    ? $num_revisions.' revisions were'
    : 'One revision was' )
    . ' made private due to unknown Bugzilla groups.';

    my $old_user = set_phab_user();

    $bug->add_comment( $bmo_error_message, { isprivate => 0 } );

    Bugzilla->set_user($old_user);
}

1;